<template>

    <div class="selectSurgeryWrap">

        <div class="mapHeader">

            <div class="stockistSearch">

                <div class="row">

                    <div class="inputWrap buttonInline">

                        <input
                                class="text withIcon"
                                id="postcodeSearch"
                                v-model="postcode_search"
                                placeholder="Your postcode"
                        />


                        <button
                                class="iconButton"
                                id="findSurgeryButton"
                        >
                            <i class="fal fa-search"></i>
                        </button>

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


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


            </div><!-- .stockistSearch -->

            <div class="stockistSearchVue">

                <div class="row" :class="[error ? 'errorWrap' : '']">

                    <div class="inputWrap buttonInline">

                        <input
                                class="text withIcon"
                                v-model="postcode_search"
                                placeholder="Your postcode"
                                @keyup="search($event)"
                        />

                        <button
                                class="iconButton"
                                @click.prevent="search($event, true)"
                        >
                            <i class="fal fa-search"></i>
                        </button>

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

                    <div class="validationMessage" v-if="error" v-text="error"></div>

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


            </div><!-- .stockistSearch -->

        </div> <!-- .mapHeader -->


        <div
                class="mapWrap"
                :class="[loading ? 'mapLoading' : '']"
        >
            <div class="mapLoader">

                <div class="loadingIcon">
                    <div class="loadingText" v-html="loadingText"></div> <!-- .loadingText -->
                </div> <!-- .loadingIcon -->

            </div> <!-- .mapLoader -->
            <div class="map mapSearch js_mapSearch" data-json-array="placesArray" data-zoom="4"></div>
        </div> <!-- .mapWrap -->

        <div class="stockistWrapper" v-show="placesLoaded">

                <a
                        id="showSearchList"
                        href="#"
                        class="textLink"
                        @click.prevent="showGPList()"
                >
                    Having trouble finding your GP surgery on the map? <span>Click here</span>
                </a>
            <div class="showResultsWrap">
            </div> <!-- .showResultsWrap -->

            <div id="stockistResults" class="results"></div>

        </div> <!-- .stockistWrapper -->


        <div class="gpSelectionWrap" v-if="data.doctor_surgery">

            <h5 class="formTitle">Selected Surgery</h5>

            <div class="surgerySelected highlightBox">

                <address-form
                    :formdata="data.doctor_surgery"
                    :errors="errors.doctor_surgery"
                    @clear-errors="clearErrors"
                ></address-form>

            </div> <!-- .surgerySelected -->

            <div class="surgeryWarning" v-if="place.disabled">
                <div class="error">
                    This surgery does not accept 3rd party requests. Please contact your GP to request this prescription.
                </div> <!-- .error -->
            </div> <!-- .surgeryWarning -->

        </div> <!-- .gpSelectionWrap -->

    </div> <!-- .selectSurgeryWrap -->

</template>



<script>

export default {

    props: [
        'data',
        'errors',
        "urlGetAvailableDoctorSurgeries",
    ],

    data: function () {
        return {
            map: false,
            postcode_search: '',
            placeIndex: -1,
            place: false,
            placesArray: [{coords: "55.378052,-3.435973"}],
            loading: true,
            mapsInit: false,
            placesLoaded: false,
            loadingText: 'Loading Map',
            error: false,
            is_editable: 0,
        };
    },

    created: function () {
        //Set default surgeries
        window.placesArray = this.placesArray;

        //events
        EventBus.$on('startGoogleMaps', function(pageNum) {
            if (!this.mapsInit) {
                this.mapsInit = true;
            }
        });
    },

    mounted: function() {

        var vm = this;


        $('body').on('click', '.js_focusMarker', function (e) {

            let place_id = $(this).data('place-id');
            let place_index = vm.getPlaceIndexByID(place_id);

            vm.place = vm.placesArray[place_index];
            vm.place.user_postcode = vm.postcode_search;

            vm.clearErrors();
            vm.data.doctor_surgery = vm.place;

            if(place_id && typeof vm.place != 'undefined') {

                var $selectedWrap = $('.gpSelectionWrap').eq(0);

                // TODO: Hi Chris, the offset() returns 'undefined' for some reason.
                $('html, body').stop(true,true).delay(200).animate({
                    //scrollTop: $selectedWrap.offset().top
                }, 1000);

            }else{
                vm.place = false;
            }


        });

        vm.googlemap();

    },

    events: {

    },

    methods: {

        clearErrors: function() {
            this.error = false;
            this.errors.doctor_surgery = {};
            this.$emit('clear-page-has-errors');
        },


        /*
         * Search surgeries
         */
        search: function(e, bypass) {

            this.clearErrors();

            var vm = this;

            vm.error = false;

            if (bypass || e.keyCode === 13) {
                vm.loading = true;
                vm.loadingText = 'Searching GP Surgeries';
                vm.getSurgeryList();
            }

        },

        /*
         * Get the place index by id
         */
        getPlaceIndexByID: function(id) {

            var vm = this,
                index = -1;

            $.each(vm.placesArray, function (i, val) {

                if (id == val.id) {
                    index = i;
                }

            });

            return index;

        },

        /*
         * Get surgery list JSON
         */
        getSurgeryList: function(){

            var vm = this;
            vm.loading = true;

            this.$http.get(this.urlGetAvailableDoctorSurgeries, {
                params: {
                    postcode: this.postcode_search,
                }
            })
                .then(function (res) {

                    if (res.data.doctor_surgeries) {
                        vm.placesArray = res.data.doctor_surgeries;
                        window.placesArray = vm.placesArray;
                        vm.placesLoaded = true;
                    }

                    if (res.data.errors) {
                        this.error = res.data.errors;
                    }

                    $('body').trigger('mapsChange');
                });

        },

        initDoctorSurgeryObject: function() {
            this.data.doctor_surgery = {
                "id": null,
                "practice_name": "",
                "address_1": "",
                "address_2": "",
                "address_3": "",
                "city": "",
                "county": "",
                "postcode": "",
                "set_is_editable": true,
            };
        },

        /*
         * Show gp list
         */
        showGPList: function() {

            if($('#stockistResults').length) {
                $('#showSearchList').hide();
                $('#stockistResults').stop().slideDown(1000);
                $('.helpText').addClass('visible');
            }

            if (! this.data.doctor_surgery) {
                this.initDoctorSurgeryObject();
            }

        },

        /*
         * Init maps
         */
        googlemap: function() {

            var vm = this;

            if ($('.js_mapSearch').length > 0) {


                vm.map = $('.js_mapSearch');

                vm.map.on('loaded', function(){
                    vm.loading = false;
                });

                vm.map.mtcGoogleMaps({
                    search: {
                        search_results: '#stockistResults',
                        search_form: '.stockistSearch',
                        max_results: 40,
                        clear_button_class: 'textLink',
                        clear_button_text: 'Clear Results',
                        result_zoom: 11,
                        autocomplete: false
                    },
                    /*
                            marker: {
                                icon: '/plugins/GoogleMaps/images/map_marker_small.png',
                                width: 40,
                                height: 55,
                                anchor_x: 20,
                                anchor_y: 26
                            },
                     */
                    info_box: {
                        close_button_markup: '<button>×</button>',
                        width: 280,
                        offset_x: -140,
                        offset_y: -24,
                        align_bottom: true,
                        close_on_click: true,
                        disable_auto_pan: false,
                        info_box_class: 'infobox'
                    },
                    styles:
                    [
                        {
                            "featureType": "all",
                            "elementType": "all",
                            "stylers": [
                                {
                                    "visibility": "on"
                                }
                            ]
                        },
                        {
                            "featureType": "administrative",
                            "elementType": "labels.text.fill",
                            "stylers": [
                                {
                                    "color": "#5F5F5F"
                                }
                            ]
                        },
                        {
                            "featureType": "landscape",
                            "elementType": "all",
                            "stylers": [
                                {
                                    "color": "#f2f2f2"
                                }
                            ]
                        },
                        {
                            "featureType": "poi",
                            "elementType": "all",
                            "stylers": [
                                {
                                    "visibility": "off"
                                }
                            ]
                        },
                        {
                            "featureType": "road",
                            "elementType": "all",
                            "stylers": [
                                {
                                    "saturation": -100
                                },
                                {
                                    "lightness": 45
                                }
                            ]
                        },
                        {
                            "featureType": "road.highway",
                            "elementType": "all",
                            "stylers": [
                                {
                                    "visibility": "simplified"
                                }
                            ]
                        },
                        {
                            "featureType": "road.arterial",
                            "elementType": "labels.icon",
                            "stylers": [
                                {
                                    "visibility": "off"
                                }
                            ]
                        },
                        {
                            "featureType": "transit",
                            "elementType": "all",
                            "stylers": [
                                {
                                    "visibility": "off"
                                }
                            ]
                        },
                        {
                            "featureType": "water",
                            "elementType": "all",
                            "stylers": [
                                {
                                    "color": "#46bcec" //#172741
                                },
                                {
                                    "visibility": "on"
                                }
                            ]
                        }
                    ],
                    map_options: {
                        disableDefaultUI: true,
                        zoomControl: true,
                        animatedZoom: false
                    }
                });

            }

        }

    }

}

</script>
