<span class="mx-2 text-secondary">|</span>
<a href="#" onclick="return showStagPopup('create-claim')">Create Claim</a>
<div class="stag-popup stag-popup-md mcp-theme-1" stag-popup-key="create-claim">
    <form action="/api/claim/createForNote" id="createClaimApp">
        <h3 class="stag-popup-title border-bottom-0 mb-0">
            <span>Create Claim</span>
            <span class="mx-2 text-secondary">|</span>
            <a href="#" v-on:click.prevent="addLine()">Add Line</a>
            <a href="#" class="ml-auto text-secondary"
               onclick="return closeStagPopup()"><i class="fa fa-times-circle"></i></a>
        </h3>
        <input type="hidden" name="noteUid" value="{{$note->uid}}">
        <table class="table table-sm table-condensed mb-3 border-left border-right border-bottom">
            <thead>
            <tr class="bg-light">
                <th class="width-100px border-bottom-0">CPT Code</th>
                <th class="width-100px border-bottom-0">Date of Service</th>
                <th class="border-bottom-0">ICDs</th>
                <th class="border-bottom-0">&nbsp;</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(line, lineIndex) in payload.lines">
                <td class="py-2">
                    <input required type="text" class="min-width-unset form-control form-control-sm" v-model="line.cpt">
                </td>
                <td class="py-2">
                    <input required type="date" class="min-width-unset form-control form-control-sm" v-model="line.dateOfService">
                </td>
                <td class="p-2 bg-light">
                    <div class="d-flex align-items-baseline">
                        <a href="#" class="text-nowrap text-primary mr-2"
                           v-on:click.prevent="addICD(lineIndex)" title="Add ICD">
                            <i class="fa fa-plus-square text-primary"></i>
                        </a>
                        <div class="flex-grow-1">
                            <div v-for="(icd, icdIndex) in line.icds" class="d-flex align-items-center" :class="icdIndex > 0 ? 'mt-1' : ''">
                                <input required type="text" class="form-control form-control-sm width-100px"
                                       data-field="icd"
                                       :data-line-index="lineIndex"
                                       :data-icd-index="icdIndex"
                                       v-model="icd.code">
                                <input required type="text" class="form-control form-control-sm flex-grow-1 ml-2"
                                       v-model="icd.description">
                                <a href="#" class="text-nowrap text-danger ml-2"
                                   v-on:click.prevent="removeICD(lineIndex, icdIndex)"
                                   v-if="line.icds.length > 1" title="Remove ICD">
                                    <i class="fa fa-trash-alt text-danger"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                </td>
                <td class="text-center pt-2">
                    <a href="#" class="text-nowrap text-danger d-block mt-1"
                       :class="payload.lines.length <= 1 ? 'opacity-60' : ''"
                       v-on:click.prevent="removeLine(lineIndex)">
                        <i class="fa fa-trash-alt text-danger"></i>
                        Remove Line
                    </a>
                </td>
            </tr>
            </tbody>
        </table>

        <div class="mt-2">
            <button type="button" class="btn btn-primary btn-sm font-weight-bold" v-on:click.prevent="saveClaim()">Create</button>
            <button type="button" class="btn btn-default border btn-sm font-weight-bold ml-2" onclick="return closeStagPopup()">Cancel</button>
        </div>
    </form>
</div>
<script>
    window.createClaimApp = new Vue({
        el: '#createClaimApp',
        delimiters: ['@{{', '}}'],
        data: {
            payload: {
                lines: [
                    {
                        cpt: '',
                        dateOfService: '{{date('Y-m-d')}}',
                        icds: window.noteReasons
                    }
                ]
            }
        },
        methods: {
            addLine: function () {
                this.payload.lines.push({
                    cpt: '',
                    dateOfService: '{{date('Y-m-d')}}',
                    icds: window.noteReasons
                });
                Vue.nextTick(() => {
                    this.initICDAutoSuggest();
                });
            },
            removeLine: function (_index) {
                if(this.payload.lines.length > 1) {
                    this.payload.lines.splice(_index, 1);
                }
            },
            addICD: function(_lineIndex) {
                this.payload.lines[_lineIndex].icds.push({
                    code: '',
                    description: '',
                });
                Vue.nextTick(() => {
                    this.initICDAutoSuggest();
                });
            },
            removeICD: function(_lineIndex, _icdIndex) {
                if(this.payload.lines[_lineIndex].icds.length > 1) {
                    this.payload.lines[_lineIndex].icds.splice(_icdIndex, 1);
                }
            },
            initICDAutoSuggest: function () {
                let self = this;
                $('#createClaimApp input[type="text"][data-field="icd"]:not([ac-initialized])').each(function () {
                    var elem = this,
                        dynID = 'icd-' + Math.ceil(Math.random() * 1000000),
                        lineIndex = $(this).attr('data-line-index'),
                        icdIndex = $(this).attr('data-icd-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 acData = elem.autocomp.getSelectedItemData();
                        self.payload.lines[lineIndex].icds[icdIndex].code = acData[0].code;
                        self.payload.lines[lineIndex].icds[icdIndex].description = acData[0].data.name;
                        return false;
                    });
                    $(elem).attr('ac-initialized', 1);
                });
            },
            saveClaim: function() {
                let form = $('form#createClaimApp').first();
                if(!form[0].checkValidity()) {
                    form[0].reportValidity();
                    return false;
                }

                $.post('/api/claim/create', {
                    noteUid: '{{$note->uid}}',
                    data: JSON.stringify(this.payload)
                }, function(_data) {
                    if (!_data.success) {
                        if (_data.message) {
                            toastr.error(_data.message);
                        }
                        else {
                            toastr.error('Unable to save the claim!');
                        }
                    }
                    else {
                        toastr.success('Claim saved!');
                        closeStagPopup();
                        fastReload();
                    }
                }, 'json')
            }
        },
        mounted: function () {
            this.initICDAutoSuggest();
        }
    })
</script>
