const calendar_week = {
    currentAjaxName: null,
    table: null,
    hfMarker: null,
    map: null,
    urls: {
        account_user_autocomplete_url: '',
        schedule_formUrl: '',
        patient_autocomplete_url: '',
        chartType_autocomplete_url: '',
        provider_autocomplete_url: '',
        health_facility_autocomplete_url: '',
        note_template_autocomplete_url: '',
        patientChartCheck_healthFacility_url: '',
        note_template_data_url: '',
        calendar_formActionUrl: '',
    },
    settings: {
        noteTemplateAccess: null,
    },
    init: function () {
        global.bindFormSubmitted();
        calendar_week.initAutoComplete();
        calendar_week.bindFilter();
        calendar_week.initCalendarTable();
    },
    initMap: function(){
        let latLong = new google.maps.LatLng(53.5564402,-113.7368218); // Edmonton, Canada
        calendar_week.map  = new google.maps.Map(document.getElementById('map-canvas'), {
            center: latLong,
            zoom: 5,
            gestureHandling: 'greedy',
            //scaleControl: false,
            streetViewControl: false,
            //rotateControl: false,
            fullscreenControl: false,
            // mapTypeControl: false,
            controlSize: 26,
            mapTypeControlOptions: {
                mapTypeIds: ['roadmap', 'satellite', 'hybrid', 'terrain']
            }
        });

        setTimeout(function () {
            let hfGeoLat = jQ('#schedule_health_facility_geoLat').val(),
                hfGeoLong =  jQ('#schedule_health_facility_geoLong').val();

            if(hfGeoLat !== '' && hfGeoLong !== ''){
                if(calendar_week.hfMarker === null){
                    calendar_week.hfMarker = new google.maps.Marker({
                        map: calendar_week.map,
                        position : new google.maps.LatLng(hfGeoLat, hfGeoLong),
                        icon:'/bundles/rxconnexion/admin/images/map-icon/HF.png'
                    });
                }else{
                    calendar_week.hfMarker.setPosition(new google.maps.LatLng(hfGeoLat, hfGeoLong));
                }
            }
        }, 1000);

    },
    initAutoComplete: function () {
        global.autocomplete.bind(calendar_week.urls.account_user_autocomplete_url, 'input[name="filter[provider_name]"]', 'input[name="filter[provider]"]');
        jQ('input[name="filter[provider_name]"]').devbridgeAutocomplete('setOptions', {
            params: {
                healthFacility_id: jQ('select[name="filter[branch]"]').val(),
            }
        });


        global.autocomplete.bind(calendar_week.urls.patient_autocomplete_url, '#schedule_patient_fullName', '#schedule_patient',{
            onSelect: function (e) {
                if(e.patientChartDetails.length){
                    var
                        chartDetail = e.patientChartDetails.split('|'),
                        chartStatus = jQ('<span>').text(chartDetail[1]),
                        chartType = jQ('<span>').text(chartDetail[2]),
                        chartDate = jQ('<span>').text(chartDetail[3]),
                        healthFacility = jQ('<span>').text(chartDetail[4]),
                        provider = jQ('<span>').text(chartDetail[5]);
                }
                var
                    //txtId = jQ('<span>').text(e.id),
                    txtName = jQ('<span>').text(e.data),
                    txtBirthDate = jQ('<span>').text(e.birthDate),
                    txtPHN = jQ('<span>').text(e.personal_health_no),
                    txtAddress = jQ('<span>').text(e.address),
                    txtMobileNos = jQ('<span>').text(e.mobileNos),
                    txtPhoneNos = jQ('<span>').text(e.phoneNos),
                    insurances = jQ('<span>').text(e.insurances),
                    rhf = jQ('<span>').text(e.referringHealthFacilities),
                    rp = jQ('<span>').text(e.referringProviders);

                jQ('#patient-detail-name').html('<strong>Full Name: </strong>');
                jQ('#patient-detail-birthDate').html('<strong>Birth Date: </strong>');
                jQ('#patient-detail-address').html('<strong>Address: </strong>');
                jQ('#patient-detail-phn').html('<strong>PHN: </strong>');
                jQ('#patient-detail-mobile').html('<strong>Mobile No(s): </strong>');
                jQ('#patient-detail-phone').html('<strong>Phone No(s): </strong>');
                jQ('#patient-detail-insurance').html('<strong>Insurance(s): </strong>');
                jQ('#patient-detail-referring-health-facility').html('<strong>Referring Health Facility: </strong>');
                jQ('#patient-detail-referring-provider').html('<strong>Referring Provider: </strong>');
                jQ('#chart-detail-provider').html('<strong>Clinician: </strong>');
                jQ('#chart-detail-health-facility').html('<strong>Branch: </strong>');
                jQ('#chart-detail-chart-type').html('<strong>Chart Type: </strong>');
                jQ('#chart-detail-chart-status').html('<strong>Chart Status: </strong>');
                jQ('#chart-detail-chart-date').html('<strong>Chart Date: </strong>');
                jQ('#patient-detail').html('<h5>Patient Details </h5>');
                jQ('#chart-latest').html('<h5>Latest Chart </h5>');
                //txtId.appendTo(jQ('#patient-detail-id'));
                txtName.appendTo(jQ('#patient-detail-name'));
                txtBirthDate.appendTo('#patient-detail-birthDate');
                txtAddress.appendTo('#patient-detail-address');
                txtPHN.appendTo('#patient-detail-phn');
                txtMobileNos.appendTo('#patient-detail-mobile');
                txtPhoneNos.appendTo('#patient-detail-phone');
                insurances.appendTo('#patient-detail-insurance');
                rhf.appendTo('#patient-detail-referring-health-facility');
                rp.appendTo('#patient-detail-referring-provider');
                if(provider !== undefined) provider.appendTo('#chart-detail-provider');
                if(healthFacility !== undefined) healthFacility.appendTo('#chart-detail-health-facility');
                if(chartType !== undefined) chartType.appendTo('#chart-detail-chart-type');
                if(chartStatus !== undefined) chartStatus.appendTo('#chart-detail-chart-status');
                if(chartDate !== undefined) chartDate.appendTo('#chart-detail-chart-date');
                jQ('#schedule_patient_city_id').val(e.city_id);
            }
        });
        global.autocomplete.bind(calendar_week.urls.provider_autocomplete_url, '#schedule_provider_fullName', '#schedule_provider');
        global.autocomplete.bind(calendar_week.urls.chartType_autocomplete_url, '#schedule_chartType_desc', '#schedule_chartType', {
            onSelect: function () {
                var params = {
                    chartType_id : jQ('#schedule_chartType').val() !== '' ? jQ('#schedule_chartType').val() : '',
                };

                jQ('#schedule_scheduleStatus_desc').devbridgeAutocomplete('setOptions', {params: params});
            }
        });
        global.autocomplete.bind(calendar_week.urls.health_facility_autocomplete_url, '#schedule_health_facility_desc', '#schedule_health_facility',{
            onSelect: function (e) {
                jQ('#schedule_health_facility_city_id').val(e.city_id);
                jQ('#schedule_health_facility_geoLat').val(e.geoLat);
                jQ('#schedule_health_facility_geoLong').val(e.geoLong);

                calendar_week.patientChartCheck(jQ('#schedule_patient').val());

                var
                    txtAddress = jQ('<span>').text(e.address),
                    txtMobileNos = jQ('<span>').text(e.mobileNos),
                    txtPhoneNos = jQ('<span>').text(e.phoneNos);

                jQ('#branch-detail-address').html('<strong>Address: </strong>');
                jQ('#branch-detail-mobileNos').html('<strong>Mobile No(s): </strong>');
                jQ('#branch-detail-phoneNos').html('<strong>Phone No(s): </strong>');
                txtAddress.appendTo('#branch-detail-address');
                txtMobileNos.appendTo('#branch-detail-mobileNos');
                txtPhoneNos.appendTo('#branch-detail-phoneNos');
            }
        });
        jQ('#schedule_note_type').unbind('change').bind('change', function () {
            if (jQ(this).val() == 'Template') {
                jQ('#schedule_note_template_description').removeClass('hide');
            } else {
                jQ('#schedule_note_template_description').addClass('hide');
            }
        });

        if(calendar_week.settings.noteTemplateAccess === false) {
            jQ('#schedule_note_type').children('option[value=Template]').addClass('hide');
        }

        global.autocomplete.bind(calendar_week.urls.note_template_autocomplete_url, '#schedule_note_template_description', '#schedule_noteTemplate', {
            onSelect: function (d) {
                global.ajax({
                    url: calendar_week.urls.note_template_data_url+'/'+d.noteTemplate_description,
                    type: 'GET',
                    beforeSend: function() {
                        jQ('#schedule_note').val('');
                    },
                    success: function(json) {
                        jQ('#schedule_note').val(json.note);
                    },
                });
            }
        });
    },
    bindFilter: function () {
        jQ('select[name="filter[branch]"]').change(function () {
            calendar_week.initAutoComplete();
            jQ('input[name="filter[provider_name]"]').focus();
        });
    },
    initCalendarTable: function () {
        if (null !== calendar_week.table) {

            // ADD DIV FOR THESE STATUSES FOR STYLING PURPOSES
            // style="background-color: ${jQ(el).css('background-color')}"
            calendar_week.table.find('td[data-status="No Show"],td[data-status="Cancelled"],td[data-status="Rescheduled"]').each(function (i, el) {
                jQ(el).html(`<div class="div-schedule"
                                          data-id="${jQ(el).data('id')}"
                                          data-time.text="${jQ(el).data('time.text')}"
                                          data-action="${jQ(el).data('action')}"
                                          data-date.text="${jQ(el).data('date.text')}"
                                    >${jQ(el).html()}</div>`).css('background-color', '');
            });

            // MERGE TD WITH THE SAME DATE
            calendar_week.table.find('tbody tr').each(function (i, tr) {
                let tds = {};
                jQ(tr).find('td').each(function (ii, td) {
                    let dateU = jQ(td).data('date.u');
                    if (dateU !== undefined) {
                        if (tds.hasOwnProperty(dateU)) {
                            tds[dateU].push(jQ(td));
                        } else {
                            tds[dateU] = [jQ(td)];
                        }
                    }
                });
                for (let key in tds) {
                    if (tds.hasOwnProperty(key)) {
                        if (tds[key].length > 1) {
                            let firstTD = tds[key][0];
                            for (let td = 1; td < tds[key].length; td++) {
                                firstTD.prepend(tds[key][td].html());
                                tds[key][td].addClass('to_remove');
                            }
                            jQ('.to_remove').remove();
                        }
                    }
                }
            });

            // MERGE TD AS ROWSPAN WITH THE SAME SCHEDULE ID
            let firstColumnBrakes = [];
            calendar_week.table.find('thead th').each(function (i, th) {
                let previousId = null,
                    cellToExtend = null,
                    rowspan = 1;
                calendar_week.table.find("td:nth-child(" + i + ")").each(function (index, e) {
                    let jThis = jQ(this),
                        id = jThis.data('id');
                    if (id !== undefined && id !== 0) {
                        // check if current row "break" exist in the array. If not, then extend rowspan:
                        if (previousId === id && id !== "" && jQ.inArray(index, firstColumnBrakes) === -1) {
                            // hide the row instead of remove(), so the DOM index won't "move" inside loop.
                            jThis.addClass('to_remove');
                            cellToExtend.attr("rowspan", (rowspan = rowspan + 1));
                        } else {
                            // store row breaks only for the first column:
                            if (i === 1) firstColumnBrakes.push(index);
                            rowspan = 1;
                            previousId = id;
                            cellToExtend = jThis;
                        }
                    }
                });
            });
            jQ('td.to_remove').remove();


            calendar_week.bindScheduleForm();
        }
    },
    bindScheduleForm: function () {

        const openForm = (_this) => {
            let requestName = 'scheduleCalendarForm',
                modal = jQ('#modal'),
                modalContent = jQ('#modal-content'),
                settings = {
                    url: calendar_week.urls.schedule_formUrl,
                    type: 'GET',
                    data: {
                        'healthFacility_id': jQ('select[name="filter[branch]"]').val(),
                        'date': jQ(_this).data('date.text'),
                        'provider_id': jQ('input[name="filter[provider]"]').val(),
                        'start_time': jQ(_this).data('time.text'),
                        'action': jQ(_this).data('action'),
                        'id': jQ(_this).data('id'),
                    },
                    beforeSend: function () {
                        modalContent.html('').addClass('has-loading');
                        modal.foundation('open');
                    },
                    success: function (json) {
                        modal.foundation('close');
                        modalContent.removeClass('has-loading').html(json.html);
                        modal.foundation('open');

                        // calendar_week.initMap();

                        global.bindFormSubmitted();
                        calendar_week.initAutoComplete();

                        jQ('#scheduleForm').unbind('submit').bind('submit', function (e) {
                            e.preventDefault();

                            let _form = jQ(this),
                                settings = {
                                    url: calendar_week.urls.calendar_formActionUrl,
                                    type: 'POST',
                                    data: _form.serialize(),
                                    beforeSend: function () {
                                        global.formSubmitted();
                                    },
                                    success: function (json) {
                                        if (json.success) {
                                            global.flashMessage('success', json.successMessages);
                                            location.reload();
                                        } else {
                                            global.formSubmittedReverse();
                                            global.flashMessage('alert', json.errorMessages);
                                        }
                                    }
                                };

                            global.ajax(settings, requestName);
                        });

                    }
                };

            calendar_week.currentAjaxName = requestName;
            global.ajaxCancel(requestName);
            global.ajax(settings, requestName);
        };

        jQ('.td-schedule').unbind('click').bind('click', function () {
            openForm(this);
        });

        jQ('.div-schedule').unbind('click').bind('click', function (e) {
            e.stopPropagation();
            openForm(this);
        });
    },
    patientChartCheck: function (patient_id) {
        jQ('#patient-chart-warning').css('display', 'none');

        var data = {};
        data['patient'] = patient_id;

        jQ.post(calendar_week.urls.patientChartCheck_healthFacility_url, data, function(response) {
            if (response.health_facility_id !== jQ('#schedule_health_facility').val()) {
                jQ('#patient-chart-warning').css('display', 'block');
            }
        }, 'json');
    },
};