<div class="popup-content-container">
    <div visit-moe no-auto-save id="medications-add-multi-preexisting-{{$note->id}}" class="w-100">
        <form show url="/api/visitPoint/addTopLevelBulkPreExisting" class="mcp-theme-1 w-100 px-3 pb-3" novalidate>
            <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
            <input type="hidden" name="category" value="MEDICATION">
            <input type="hidden" name="dataJson">

            <table class="table table-sm table-bordered stag-sheet allow-row-addition bg-white mb-2 point-table read">
                <thead>
                <tr class="bg-light">
                    <th class="border-bottom-0 text-secondary">Medication</th>
                    <th class="border-bottom-0 text-secondary width-100px">Start Date</th>
                    <th class="border-bottom-0 text-secondary width-100px">Prescriber</th>
                    <th class="border-bottom-0 text-secondary w-25">Subjective</th>
                    <th class="border-bottom-0 text-secondary w-25">Plan</th>
                    <th class="border-bottom-0 text-secondary width-40px"></th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td class="p-0">
                        <input type="text" key="name" bucket="data" required
                               stag-suggest
                               stag-suggest-ep="/fdb-med-suggest-v2/json">
                        <input type="hidden" key="routedMedId" bucket="data">
                        <input type="hidden" key="routedDosageFormMedId" bucket="data">
                        <input type="hidden" key="gcnSeqno" bucket="data">
                        <input type="hidden" key="medId" bucket="data">
                    </td>
                    <td class="p-0">
                        <input type="date" key="start_date" bucket="data">
                    </td>
                    <td class="p-0">
                        <input type="text" key="prescriber" bucket="data">
                    </td>
                    <td class="p-0">
                        <textarea rows="1" key="value" bucket="childReviewData"></textarea>
                    </td>
                    <td class="p-0">
                        <textarea rows="1" key="value" bucket="childPlanData"></textarea>
                    </td>
                    <td class="px-2 align-middle text-center text-nowrap">
                        <a href="#" class="delete-line mr-2"><i class="fa fa-trash-alt text-danger on-hover-opaque"></i></a>
                        <a href="#" class="add-line mr-2"><i class="fa fa-plus text-primary on-hover-opaque"></i></a>
                    </td>
                </tr>
                </tbody>
            </table>
            <div class="d-flex align-items-center">
                <button class="btn-save-lines btn btn-sm btn-primary mr-2">Save</button>
                <button class="btn btn-sm btn-default border bg-white" onclick="closeStagPopup(); return false;">Close</button>
            </div>
        </form>
    </div>
</div>
<script>
    (function () {
        function init() {

            let parentSegment = $('#medications-add-multi-preexisting-{{$note->id}}');
            parentSegment.find('input[stag-suggest][key="name"]')
                .off('stag-suggest-selected')
                .on('stag-suggest-selected', (_e, _input, _data) => {
                    $(_input).closest('tr').find('input[key="routedMedId"]').val(_data.routed_med_id);
                    $(_input).closest('tr').find('input[key="routedDosageFormMedId"]').val(_data.routed_dosage_form_med_id);
                    $(_input).closest('tr').find('input[key="gcnSeqno"]').val(_data.gcn_seqno);
                    $(_input).closest('tr').find('input[key="medId"]').val(_data.medid);
                    return false;
                });

            function getRowBefore(_tr) {
                return _tr.prev();
            }

            function moveToPrevRowInput(_td) {
                let tr = getRowBefore(_td.closest('tr'));
                tr.find('td:eq(' + _td.index() + ')').find('input, textarea').first().focus();
            }

            function getRowAfter(_tr) {
                return _tr.next();
            }

            function getOrCreateRowAfter(_tr) {
                let tr = getRowAfter(_tr);
                if(!tr.length) {
                    tr = newRow(_tr).insertAfter(_tr);
                }
                return tr;
            }

            function createRowAfter(_tr) {
                return newRow(_tr).insertAfter(_tr);
            }

            function newRow(_tr) {
                let newTr = _tr.clone(true);
                newTr.find('input, textarea').val('');
                newTr.find('textarea').attr('rows', 1);
                newTr.find('[stag-suggest-initialized]').removeAttr('stag-suggest-initialized');
                return newTr;
            }

            function createAndMoveToNextRowInput(_td) {
                let tr = createRowAfter(_td.closest('tr'));
                tr.find('td:eq(' + _td.index() + ')').find('input, textarea').first().focus();
            }

            function moveToNextRowInput(_td, _forceCreate = false) {
                let tr = _forceCreate ? getOrCreateRowAfter(_td.closest('tr')) : getRowAfter(_td.closest('tr'));
                if(tr.length) {
                    tr.find('td:eq(' + _td.index() + ')').find('input, textarea').first().focus();
                }
            }

            function moveToPrevInput(_td) {
                _td.prev().find('input, textarea').first().focus();
            }

            function moveToNextInput(_td) {
                _td.next().find('input, textarea').first().focus();
            }

            function generateData(_parentSegment) {
                let lines = [];
                _parentSegment.find('.stag-sheet tbody tr').each(function() {
                    let line = {
                        data: {},
                        childReviewData: {},
                        childPlanData: {}
                    };
                    $(this).find('input, textarea').each(function() {
                        line[$(this).attr('bucket')][$(this).attr('key')] = this.value;
                    });
                    line.data = JSON.stringify(line.data);
                    line.childReviewData = JSON.stringify(line.childReviewData);
                    line.childPlanData = JSON.stringify(line.childPlanData);
                    lines.push(line);
                });
                return JSON.stringify(lines);
            }

            parentSegment
                .off('keydown', '.stag-sheet input, .stag-sheet textarea')
                .on('keydown', '.stag-sheet input, .stag-sheet textarea', function(_e) {
                    switch (_e.which) {
                        case 13: // ENTER: If shift NOT pressed, move to next row same column
                            if (!_e.shiftKey) {
                                if($(this).closest('.stag-sheet').is('.allow-row-addition')) {
                                    createAndMoveToNextRowInput($(this).closest('td'));
                                }
                                else {
                                    moveToNextRowInput($(this).closest('td'), false);
                                }
                                return false;
                            }
                            break;
                        case 38: // UP: If caret already at 0, move up to prev row same column
                            if (this.selectionStart === this.selectionEnd && this.selectionStart === 0) {
                                moveToPrevRowInput($(this).closest('td'));
                                return false;
                            }
                            break;
                        case 40: // DOWN: If caret already at end, move down to next row same column
                            if (this.selectionStart === this.selectionEnd && this.selectionStart === this.value.length) {
                                moveToNextRowInput($(this).closest('td'));
                                return false;
                            }
                            break;
                        case 37: // LEFT: If caret already at 0, move left to prev column
                            if (this.selectionStart === this.selectionEnd && this.selectionStart === 0) {
                                moveToPrevInput($(this).closest('td'));
                                return false;
                            }
                            break;
                        case 39: // DOWN: If caret already at end, move right to next column
                            if (this.selectionStart === this.selectionEnd && this.selectionStart === this.value.length) {
                                moveToNextInput($(this).closest('td'));
                                return false;
                            }
                            break;
                        case 8: // BACKSPACE: If caret already at 0, move left to prev column
                            break;
                    }

                });

            parentSegment
                .off('click.delete-line', '.stag-sheet .delete-line')
                .on('click.delete-line', '.stag-sheet .delete-line', function() {
                    let tr = $(this).closest('tr');
                    let isFirst = (tr.index() === 0);
                    if(isFirst) {
                        newRow(tr).insertAfter(tr);
                    }
                    tr.remove();
                    return false;
                });

            parentSegment
                .off('click.add-line', '.stag-sheet .add-line')
                .on('click.add-line', '.stag-sheet .add-line', function() {
                    let tr = $(this).closest('tr');
                    newRow(tr).insertAfter(tr);
                    initStagSuggest();
                    return false;
                });

            parentSegment
                .off('click.btn-save-lines', '.btn-save-lines')
                .on('click.btn-save-lines', '.btn-save-lines', function() {
                    parentSegment.find('[name="dataJson"]').val(generateData(parentSegment));
                    saveVisitForm(this, false, true);
                    return false;
                });

            initStagSuggest();
        }

        addMCInitializer('medications-add-multi-preexisting-{{$note->id}}', init, '#medications-add-multi-preexisting-{{$note->id}}');
    }).call(window);
</script>
