<template>

    <section class="inline-template-wrapper">

        <form autocomplete="off" class="medicationListForm">

            <div class="medicationList" v-show="formdata.prescription_items.length">

                <div
                    class="medicationBox"
                    v-for="(medication, medIndex) in formdata.prescription_items"
                    :class="[medication.errors.length ? 'open' : '']"
                    :data-med-index="medIndex"
                    >

                    <div class="innerBox" :class="[hasErrors(medication) ? 'boxError' : '']" v-if="medication">

                        <h4 class="medicationTitle" v-html="medication.name" @click.prevent="showHideMedBoxes($event)"></h4>

                        <div class="medicationFields">

                            <div class="row" :class="[medication.errors.quantity ? 'errorWrap' : '']">

                                <label>Prescription quantity</label>

                                <div class="inputWrap">

                                    <chosen
                                            :options="quantities"
                                            placeholder="Select quantity"
                                            v-model="medication.quantity"
                                            class="no-chosen selectQuantity"
                                            @input="medication.errors.quantity = false"
                                            label="text"
                                            trackBy="value"

                                    ></chosen>

                                </div> <!-- .inputWrap -->

                                <div
                                    class="validationMessage"
                                    v-if="medication.errors.quantity"
                                    v-html="medication.errors.quantity"
                                    ></div>

                            </div> <!-- .row -->



                            <div class="row" :class="[medication.errors.refill_date ? 'errorWrap' : '']">

                                <label>Due date</label>

                                <div class="inputWrap">

                                    <div class="datepickerWrap">
                                        <datepicker
                                                class="datepicker"
                                                v-model="medication.refill_date"
                                                @input="medication.errors.refill_date = false"
                                                @blur="medication.errors.refill_date = false"
                                                :options="{
                                                    dateFormat: 'dd/mm/yy',
                                                    altFormat: 'yy-mm-dd',
                                                    minDate: '+7d'
                                                }"
                                                placeholder="dd/mm/yyyy"
                                                :id="'prescription_item_' + medIndex"
                                        ></datepicker>
                                    </div>

                                </div> <!-- .inputWrap -->

                                <div
                                    class="validationMessage"
                                    v-if="medication.errors.refill_date"
                                    v-html="medication.errors.refill_date"
                                    ></div>

                            </div> <!-- .row -->

                            <div class="row" :class="[medication.errors.additional_info ? 'errorWrap' : '']">

                                <label>Do you need this item customising?</label>

                                <div class="inputWrap">

                                    <textarea
                                        placeholder="Please enter any additional here"
                                        v-model="medication.additional_info"
                                        @input="medication.errors.additional_info = false"
                                        ></textarea>

                                </div> <!-- .inputWrap -->

                                <div
                                    class="validationMessage"
                                    v-if="medication.errors.additional_info"
                                    v-html="medication.errors.additional_info"
                                    ></div>

                            </div> <!-- .row -->

                            <div class="row" :class="[medication.errors.one_off_prescription ? 'errorWrap' : '']">

                                <div class="inputWrap">

                                    <input
                                        :id="'one_off_prescription_' + medIndex"
                                        type="checkbox"
                                        v-model="medication.one_off_prescription"
                                        :true-value="0"
                                        :false-value="1"
                                        @change="medication.frequency_days = false; medication.errors.one_off_prescription = false"
                                        >
                                        <label :for="'one_off_prescription_' + medIndex">
                                            Repeat this order
                                            <i class="hoverFX"></i>
                                        </label>

                                </div> <!-- .inputWrap -->

                                <div
                                    class="validationMessage"
                                    v-if="medication.errors.one_off_prescription"
                                    v-html="medication.errors.one_off_prescription"
                                    ></div>

                            </div> <!-- .row -->

                            <div class="row" :class="[medication.errors.frequency_days ? 'errorWrap' : '']" v-show="!medication.one_off_prescription">

                                <label>Prescription frequency (days)</label>

                                <div class="inputWrap">

                                    <chosen
                                            :options="frequencies"
                                            placeholder="Select frequency"
                                            v-model="medication.frequency_days"
                                            class="no-chosen selectFrequency"
                                            @input="medication.errors.frequency_days = false"
                                            label="text"
                                            trackBy="value"

                                    ></chosen>

                                    <input
                                        type="number"
                                        v-show="doShowFrequencyOther(medication.frequency_days)"
                                        label="Number of days"
                                        v-model="medication.frequency_days"
                                        class="frequencyDays"
                                    />


                                </div> <!-- .inputWrap -->

                                <div
                                    class="validationMessage"
                                    v-if="medication.errors.frequency_days"
                                    v-html="medication.errors.frequency_days"
                                    ></div>

                            </div> <!-- .row -->

                            <transition name="fade">

                                <div class="savedMed" v-if="medication.saved">

                                    <div class="success">
                                        <p>Medication has been saved</p>
                                    </div> <!-- .success -->

                                </div> <!-- .savedMed -->

                                <div class="savedMed" v-else-if="medication.errors">

                                    <div class="error" v-for="error in medication.errors" v-if="error">
                                        <p v-html="error"></p>
                                    </div> <!-- .success -->

                                </div> <!-- .savedMed -->

                            </transition>

                            <div class="buttonGroup">

                                <div class="boxLoading" v-if="loading">
                                    <i class="fal fa-circle-notch fa-spin"></i>
                                </div> <!-- .boxLoading -->

                                <button
                                    type="button"
                                    class="button buttonSmall buttonOutlined"
                                    @click.prevent="saveMedication($event, medIndex)"
                                    >Save</button>

                                <button
                                    type="button"
                                    class="button buttonSmall buttonText"
                                    @click.prevent="removeMedication($event, medIndex)"
                                    >
                                    Remove
                                </button>

                            </div> <!-- .buttonWrapper -->

                        </div> <!-- .innerFields -->

                    </div> <!-- .innerBox -->

                </div> <!-- .medicationBox -->

            </div> <!-- .medicationList -->

            <div class="medicationSearch" :class="[showMedicationSearchResults ? 'resultsActive' : '']">

                <div class="row">

                    <div class="inputWrap buttonInline">

                        <div class="row" :class="[errors.prescription_items_error ? 'errorWrap' : '']">

                            <input
                                type="text"
                                v-model="medicationQuery"
                                @input="medicationSearch()"
                                @focus="showMedicationSearchResults = true; errors.prescription_items_error = false"
                                placeholder="Search medication and appliances"
                                name="medication_search"
                            />

                            <button
                                type="submit"
                                class="button"
                                @click.prevent="addMedicationIfValid()"
                            >
                                Add item
                            </button>

                        </div><!-- .inputWrap -->

                        <div
                            class="validationMessage"
                            v-if="errors.prescription_items_error"
                            v-html="errors.prescription_items_error"
                        ></div>

                    </div> <!-- .row -->

                    <div
                        class="medicationResults"
                        :class="[showMedicationSearchResults && medicationQuery.length ? 'resultsVisible' : '']"
                        >

                        <div class="scrollContain">

                            <div class="innerResults">


                                <ul v-if="medicationResults.length">
                                    <li v-for="medication in medicationResults">
                                        <a
                                            href="#"
                                            @click.prevent="selectMedicationResult(medication)"
                                            v-html="medication"
                                            ></a>
                                    </li>
                                </ul>

                                <ul v-if="!medicationResults.length">
                                    <li>
                                        No medications found
                                    </li>
                                </ul>

                            </div> <!-- .innerResults -->

                        </div> <!-- .scrollContain -->

                    </div> <!-- .medicationResults -->

                </div> <!-- .row -->

            </div> <!-- .medicationSearch -->

        </form>

        <div class="helpBox darkBg">

            <h3>Need your prescription sooner?</h3>

            <p>If your prescription is due in 7 days we can help</p>

            <a href="/contact/" class="buttonAlt">Get in touch<i class="fal fa-long-arrow-right"></i></a>

        </div> <!-- .helpBox -->


    </section>

</template>


<script>

export default {

    props: [
        "urlSavePrescription",
        "urlGetAvailableNhsMedications",
        "urlCheckMedicationNameIsValid",
        "formdata",
        "errors",
    ],

    data: function () {
        return {
            medicationQuery: '',
            medicationResults: [],
            quantities: [
                { text: '1 pack', value: 1 },
                { text: '2 packs', value: 2 },
                { text: '3 packs', value: 3 },
                { text: '4 packs', value: 4 },
                { text: '5 packs', value: 5 },
                { text: '6 packs', value: 6 },
                { text: '7 packs', value: 7 },
                { text: '8 packs', value: 8 },
                { text: '9 packs', value: 9 },
                { text: '10 packs', value: 10 }
            ],
            frequencies: [],
            showMedicationSearchResults: false,
            loading: false,
            canProceed: false,
            timeout: null,
            currentMedicationSearchRequest: null,
        };
    },

    created: function () {

        //Build the frequency list
        this.buildFrequencies();

    },

    mounted: function() {

        var vm = this;


    },


    computed: {

        frequencies_numeric: function() {
            let output = [];

            for (let i = 0; i < this.frequencies.length; i++) {
                if (! isNaN(this.frequencies[i].value)) {
                    output.push(this.frequencies[i].value);
                }
            }

            return output;
        },

    },


    methods: {

        doShowFrequencyOther: function(value) {
            let do_show = false;

            if (value && ! this.frequencies_numeric.includes(""+value)) {
                do_show = true;
            }

            return do_show;
        },


        /*
        * Unset medication from list based on index
         */
        unsetMedication: function(medIndex) {

            var vm = this;

            if(typeof vm.medications[medIndex] != 'undefined') {
                vm.medications.splice(medIndex, 1);
                //vm.medicationListUpdated();
            }

        },

        /*
        * Build frequency (no. of days list)
         */
        buildFrequencies: function() {

            this.frequencies = [
                { text: 'Every 28 days', value: '28' },
                { text: 'Every 56 days', value: '56' },
                { text: 'Every 84 days', value: '84' },
                { text: 'Every ... days', value: 'other' },
            ];

        },



        /*
        * Search medications
        */
        medicationSearch: function() {

            this.medicationResults = [
                "Searching...",
            ];

            var vm = this,
                query = this.medicationQuery;

            this.$http.get(this.urlGetAvailableNhsMedications, {
                params: {
                    search_term: query
                },
                before: function(request) {
                    if (this.currentMedicationSearchRequest) {
                        this.currentMedicationSearchRequest.abort();
                    }
                    this.currentMedicationSearchRequest = request;
                }

            }).then(function (res) {
                var results = res.data.medications;

                if(results.length) {
                    vm.medicationResults = results;
                }else{
                    vm.medicationResults = [];
                }
            });


        },

        /*
        * Add selected medication to search box
         */
        selectMedicationResult: function(medication){
            this.medicationQuery = medication;
            this.showMedicationSearchResults = false;
        },


        addMedicationIfValid: function()
        {
            this.$http.post(this.urlCheckMedicationNameIsValid, {
                search_term: this.medicationQuery,
            })
            .then(function (res) {
                if (res.data.is_valid) {
                    this.addMedication();
                }
            });
        },

        /*
        * Add a new medication
        */
        addMedication: function() {

            window.ee.sendEvent('checkout', {
                stepName: 'item_added',
            });

            var vm = this,
                medication = vm.medicationQuery;

            //Create data
            var medicationObj = {
                name: medication,
                quantity: 1,
                refill_date: '',
                one_off_prescription: 1,
                additional_info: '',
                frequency_days: false,
                display: {
                    open: true,
                    hidden: true
                },
                is_valid: false,
                errors: {
                    quantity: false,
                    refill_date: false,
                    one_off_prescription: false,
                    additional_info: false,
                    frequency_days: false,
                }
            };

            vm.medicationQuery = '';
            this.formdata.prescription_items.push(medicationObj);
            //vm.medicationListUpdated();

            this.$emit('set-page-has-errors');

            //Reveal the new box
            setTimeout(function() {

                var nextIndex = vm.formdata.prescription_items.length - 1,
                    $box = $('.medicationBox[data-med-index="' + nextIndex + '"]');

                if($box.length) {

                    $box.slideDown(400, function() {

                        vm.formdata.prescription_items[nextIndex].display.open = false;

                        $('html,body').animate({
                            scrollTop: $box.offset().top
                        }, 800, function () {

                            if(!$box.hasClass('addingBox')) {

                                $box.addClass('addingBox');

                                vm.formdata.prescription_items[nextIndex].display.hidden = false;

                                vm.showHideMedBoxes({
                                    target: '.medicationBox[data-med-index="' + nextIndex + '"] .medicationTitle'
                                }, true);
                            }
                        });

                    });

                }

            },200);


        },


        /*
        * Remove a medication
        */
        removeMedication: function(event, medIndex) {

            //delete this.formdata.prescription_items[medIndex];
            this.formdata.prescription_items.splice(medIndex, 1);

            //var vm = this,
            //    $box = $(event.target).parents('.medicationBox');


            //$box.slideUp(1800, function() {
            //    //this.formdata.prescription_items.splice(medIndex, 1);
            //});

            this.$emit('clear-page-has-errors');

        },

        /*
        * Save medication
        */
        saveMedication: function(event, medIndex) {

            var vm = this,
                $box = $(event.target).parents('.medicationBox');

            if(!vm.loading) {

                vm.loading = true;

                const itemsBeforeAjax = this.formdata.prescription_items;

                this.errors.prescription_items_error = null;

                this.$http.post(this.urlSavePrescription, {
                    formdata: { prescription_items: this.formdata.prescription_items  }
                })
                    .then(function (res) {


                        if (res.data.errors.prescription_items) {
                            //vm.medications = res.data.errors.prescription_items;
                            vm.formdata.prescription_items = res.data.errors.prescription_items;

                            //Workaround to maintain display object
                            for(let i=0; i<itemsBeforeAjax.length; i++) {
                                vm.formdata.prescription_items[i].display = itemsBeforeAjax[i].display;
                            }

                            this.$emit('set-page-has-errors');
                        } else {
                            this.$emit('clear-page-has-errors');
                        }

                        for(let i in vm.formdata.prescription_items) {

                            vm.formdata.prescription_items[i].saved = true;

                            for(let k in vm.formdata.prescription_items[i].errors) {

                                let err = vm.formdata.prescription_items[i].errors[k];

                                if(!err.length || !err) {
                                    vm.formdata.prescription_items[i].saved = true;
                                }else{
                                    vm.formdata.prescription_items[i].saved = false;
                                }


                            }

                            Vue.set(vm.formdata.prescription_items, i, vm.formdata.prescription_items[i]);


                        }


                        vm.loading = false;
                        //vm.medicationListUpdated();

                    })
                    .catch(function (error) {
                        vm.canProceed = false;
                        vm.loading = false;
                        vm.$emit('set-page-has-errors');
                        //vm.medicationListUpdated();
                    });
            }

        },



        /*
        * Check for errors
         */
        hasErrors: function(medication) {

            var hasError = false;

            if( medication.hasOwnProperty('errors') ) {

                for(var prop in medication.errors) {

                    if(medication.errors[prop]) {
                        hasError = true;
                    }
                }

            }

            return hasError;

        },

        /*
        * Show / hide functionality on medication boxes
         */
        showHideMedBoxes: function(e, isObj) {

            var vm = this;

            //Show/hide functionality on medication boxes

            if(typeof isObj == 'undefined') {
                e.stopPropagation();
            }

            var $title = $(e.target),
                $section = $title.next('.medicationFields'),
                $box = $title.parents('.medicationBox'),
                medIndex = parseInt($box.attr('data-med-index'));


            //Add classes while animating
            if($box.hasClass('open')) {
                $box.addClass('closing');
            }else{
                $box.addClass('opening');

            }

            //Show hide menus
            $section.stop().slideFadeToggle(1000, function () {

                //Set visibility classes and display values
                if ($(this).is(':visible')) {
                    $box.addClass('open');
                    //vm.formdata.prescription_items[medIndex].display.open = true;
                } else {
                    $box.removeClass('open');
                    //vm.formdata.prescription_items[medIndex].display.open = false;
                }

                //Remove animation classes
                $box
                    .removeClass('opening')
                    .removeClass('closing')
                    .removeClass('addingBox');


            });


        },

    },

}

</script>

