var newMarkersAdded = false;

var globalWorkOrderLoc;
var globalWorkOrderUrls;
var globalWorkOrderParams;

var _isMobileWO;

function clearMarkers() {
    for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(null);
    }
    markers = [];
}

function fitMapBounds() {
    if ($('#map-container').hasClass('active') && newMarkersAdded) {
        let bounds = new google.maps.LatLngBounds(null);

        for (var i = 0; i < markers.length; i++) {
            bounds.extend(markers[i].getPosition());
        }

        map.fitBounds(bounds);

        google.maps.event.addListenerOnce(map, "idle", function () {
            if (map.getZoom() > 15) {
                map.setZoom(15);
            }
        });

        newMarkersAdded = false;
    }
}

function addMarker(markerData) {
    var blackPin = {
        path: "M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z",
        fillColor: '#333',
        fillOpacity: 1,
        strokeColor: '#fff',
        strokeWeight: 2,
        rotation: 0,
        scale: 2,
        anchor: new google.maps.Point(12, 24),
    };

    var circleIcon = {
        path: google.maps.SymbolPath.CIRCLE,
        fillColor: 'orange',
        fillOpacity: 1,
        strokeColor: 'white',
        strokeWeight: 2,
        scale: 18
    };

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ address: markerData.address }, function (results, status) {
        if (status === 'OK') {
            let marker = new google.maps.Marker({
                position: results[0].geometry.location,
                map: map,
                title: markerData.title,
                icon: markerData.isCircle ? circleIcon : blackPin
            });

            markers.push(marker);
            newMarkersAdded = true;

            let contentString =
                '<div style="width: 200px;">' +
                '<div style="border-bottom: 1px solid #ccc;" class="mb-8 model-simple-title p-b-10">' + markerData.title + '</div>' +
                '<div style="font-weight: 500;">' + markerData.subject + '</div>' +
                '<div class="mb-8">' + markerData.address + '</div>' +
                '<div class="mb-8">' + markerData.acKeyView + '</div>' +
                '<div>' +
                '<div class="services-card-label ' + markerData.dateClass + '"><span style="margin-right:2px"> <i class="far fa-calendar alt"></i> </span> <span>' + markerData.date + '</span></div>' +
                '<div class="services-card-label pull-right ' + markerData.percentageClass + '"><span>' + markerData.percentageText + '</span></div>' +
                '</div>' +
                '</div>';

            let infowindow = new google.maps.InfoWindow({
                content: contentString
            });
                        
            marker.addListener('click', function () {
                infowindow.open(map, marker);
            });
        } else {
            console.error('Geocode was not successful for the following address: ' + markerData.address);
        }
    });
}

function setFromDailyPlanButtonState() {
    $("#data-from-daily-plan").prop('checked', function () {
        return localStorage.getItem('WoFromDailyPlan') === "true"
    });
}

function initWorkOrdersSvc(localization, urls, params) {

    globalWorkOrderLoc = localization;
    globalWorkOrderUrls = urls;
    globalWorkOrderParams = params;

    _isMobileWO = globalWorkOrderParams.isMobile === 'True' ? true : false;

    if (!_isMobileWO) {

        $("#mainGrid").appendTo(".document-list");

        $('#X').addClass('active').css('border-bottom', '4px solid #faaf14');

        $(".datepicker").datepicker({
            format: 'dd.mm.yyyy',
            language: $('#languageDate').val()
        }).on('changeDate', function () {
            $(this).datepicker('hide');
            $.fn.dataTable.reload($mainGridTable);
        });

    }
    else {
        $("#mainGrid").appendTo(".document-list-no-footer");
    }

    $('.js-switch').on('change', function () {
        localStorage.setItem('WoFromDailyPlan', this.checked);
        $.fn.dataTable.reload($mainGridTable);
    });

    setFromDailyPlanButtonState();
    $mainGridTable = $('#mainGrid');

    var mainTable = $mainGridTable.DataTable({
        initComplete: function (settings, json) {
            $('.menu-open-button').on("click", function () {
                event.preventDefault();
                event.stopPropagation();
                $(this).toggleClass('active');
            });

            $('.menu-item').on("click", function () {
                event.preventDefault();
                event.stopPropagation();
            });
        },
        ajax: {
            url: $mainGridTable.attr('data-url'),
            data: function (d) {
                d.DocTypes = $('#DocTypes').val();
                d.Statuses = $('#Status').val();
                d.Product = $("#IdentFilterSearch").val();
                d.Keywords = $('.search-input[name="Keywords"]').val();
                d.ProductionType = $("#ProdType").val();
                d.DataFromDailyPlan = $("#data-from-daily-plan").is(":checked");
                d.DateFrom = _isMobileWO ? $("#mDateFrom").val() : reformatDate($("#DateFrom").val());
                d.DateTo = _isMobileWO ? $("#mDateTo").val() : reformatDate($("#DateTo").val());
                d.Idents = $('#ident').val();
            }
        },
        columns: [
            {
                class: 'border-bottom',
                orderable: false,
                render: function (data, type, full) {

                    var tooltip = '<span data-toggle="tooltip" class="card-caption" data-original-title = "' + full.Product + '">' + full.Product + ' </span> ';

                    return "<span style = 'width:100rem;position: relative;display: table-cell;height: 70px;'>" + tooltip + " </span>" +

                        '<nav class="menu hidden">' +
                        '    <label class="menu-open-button" for="menu-open-' + full.AcKey + '" >' +
                        '        <span class="hamburger hamburger-1"></span>' +
                        '        <span class="hamburger hamburger-2"></span>' +
                        '        <span class="hamburger hamburger-3"></span>' +
                        '    </label>' +

                        '    <a href="#" class="menu-item"> <i class="fa fa-bar-chart"></i> </a>' +
                        '    <a href="#" class="menu-item"> <i class="fa fa-plus"></i> </a>' +
                        '    <a href="#" class="menu-item"> <i class="fa fa-heart"></i> </a>' +
                        '    <a href="#" class="menu-item"> <i class="fa fa-envelope"></i> </a>' +
                        '</nav>';
                }
            },
            {
                data: "Consignee",
                name: "Consignee",
                className: "dt-body-left",

                render: function (data, type, full) {
                    return type === 'display' ?
                        '<div><span style="font-weight: 600;">' + data + '</span></div>' +
                        '<div><span>' + full.Address + '</span></div>' : data;
                }
            },
            {
                data: "AcKeyDisplay",
                name: "AcKey",
                className: "dt-body-left",

                render: function (data, type, full) {
                    var hidden = full.WoExOperRegCount == "0" ? 'hidden' : '';
                    return type === 'display' ?
                        '<span>' + data + '</span>' +
                        '<div class="pulsating-circle pull-right ' + hidden + '"</div >' : data;
                }
            },
            {
                data: 'Date',
                name: "adDate",
                render: function (data, type, full) {
                    var dateClass = 'label-default';
                    if (isPastDate(data)) {
                        dateClass = 'label-danger';
                    }

                    var percentageClass = 'label-default';
                    var percentageText = full.CompletedPrc;
                    if (+percentageText == 0) {
                        percentageClass = 'label-success';
                        percentageText = globalWorkOrderLoc.opened;
                    } else if (+percentageText >= 100) {
                        percentageText = globalWorkOrderLoc.finished;
                    } else {
                        percentageText += '%';
                        percentageClass = 'label-primary';
                    }

                    var markerData = {
                        title: full.Product,
                        subject: full.Consignee,
                        address: full.Address,
                        acKeyView: full.AcKeyDisplay,
                        dateClass: dateClass,
                        date: data,
                        percentageClass: percentageClass,
                        percentageText: percentageText,
                        isCircle: false
                    };
                    addMarker(markerData);

                    return type === 'display' ?
                        '<div><div class="services-card-label ' + dateClass + '"><span style="margin-right:2px"> <i class="far fa-calendar alt"></i> </span> <span>' + data + '</span></div>' +
                        '<div class="services-card-label pull-right ' + percentageClass + '"><span>' + percentageText + '</span></div></div>' : data;
                }
            }
        ],
        createdRow: function (row) {
            $(row).css('cursor', 'pointer');
        },
        drawCallback: function (settings) {
            setTimeout(function () {
                fitMapBounds();
            }, 750);
            $('#X > span:last-child').text(settings.json.prop.All);

            if ($("#ProdType").val() === "MF") {
                $('#P > span:last-child').text(settings.json.prop.Planned);
                $('#O > span:last-child').text(settings.json.prop.Opened);
                $('#I > span:last-child').text(settings.json.prop.Reserved);
                $('#R > span:last-child').text(settings.json.prop.Released);
                $('#D > span:last-child').text(settings.json.prop.InProgress);
                $('#E > span:last-child').text(settings.json.prop.PartialyFinished);
                $('#Z > span:last-child').text(settings.json.prop.Finished);
            } else {
                $('#N > span:last-child').text(settings.json.prop.Opened);
                $('#L > span:last-child').text(settings.json.prop.Released);
                $('#D > span:last-child').text(settings.json.prop.InProgress);
                $('#I > span:last-child').text(settings.json.prop.Finished);
            }

            $("[data-toggle='tooltip']").tooltip({
                container: 'body'
            }),
                $("[data-toggle=popover]").popover({

                    html: true,
                    container: "body",
                    trigger: 'hover',
                    content: function () {

                        $.ajax({
                            url: $(this).attr('data-url'),
                            type: 'POST',
                            async: false,
                            data: {
                                Key: $(this).attr('data-key'),
                                ItemType: ""
                            },
                            success: function (response) {
                                getWOOperRegTable(response);

                            }
                        });

                        return $('#operPopover').html();
                    }
                }).click(function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                });
        }
    }).on('click', 'tr', function () {
        var data = mainTable.row($(this)).data();
        window.location.href = "Manufacturing/WorkOrderOperations?key=" + data.AcKey;
    });

    $("select").off("change.tableReload");
    $("select").on("change.tableReload", function (e) {
        setFiltersMobile();
        $.fn.dataTable.reload($mainGridTable);
    });
    
    $(".btn-toolbar > button.btn").on("click", function () {
        var buttonId = $(this).attr('id');
        var color = $(this).css("color");

        if (buttonId != 'X') {
            $('#X').removeClass('font-bold').removeClass('active').css("border-bottom", "");
        } else {
            color = "#faaf14";
            $(".btn-toolbar > button.btn").each(function () {
                $(this).removeClass('font-bold').removeClass('active').css("border-bottom", "");
            });
        }

        $(this).toggleClass('active').toggleClass('font-bold');

        if ($(this).hasClass('active')) {
            $(this).css("border-bottom", "4px solid " + color);
        } else {
            $(this).css("border-bottom", "")
        }

        let text = [""];
        $(".btn-toolbar > button.btn").each(function () {
            if ($(this).hasClass('active') && buttonId != 'X') {
                text.push($(this).attr('id'))
            }
        });

        if (text == "") {
            $('#X').addClass('font-bold').addClass('active').css("border-bottom", "4px solid #faaf14");
        }

        $('#Status').val(text);
        $.fn.dataTable.reload($mainGridTable)
    });

    setFiltersMobile();

    $('.btn-back').on("click", function () {
        if ($("#filter-container").hasClass("active")) {
            $(".divided-content").addClass("divided-content-side-closed").removeClass("divided-content-side-opened");
        } else {
            $('#filtersTabs>.tab-pane').removeClass("active");
            $('#filtersTabs>#filter-container').addClass("fade").addClass("in").addClass("active");
        }
    });

    $('#filter').on("click", function () {
        $('#map-tab').removeClass("active");
        $('#filter-tab').addClass("active");

        $('.tab-buttons').show();
        $('#map-container').hide();

        $('#map-tab').hide();
        $('#filter-tab').show();

        $('#filtersTabs>.tab-pane').removeClass("active");
        $('#filtersTabs>#filter-container').addClass("fade").addClass("in").addClass("active");
        $(".divided-content").addClass("divided-content-side-opened").removeClass("divided-content-side-closed");
    });

    $('#map').on("click", function () {
        $('#filtersTabs>.tab-pane').removeClass("active");
        $('#filter-tab').removeClass("active");

        $('.tab-buttons').hide();
        $('#map-container').show();

        $('#map-tab').show();
        $('#filter-tab').hide();

        $('#map-tab').addClass("active");
        $('#map-container').addClass("fade").addClass("in").addClass("active");
        $(".divided-content").addClass("divided-content-side-opened").removeClass("divided-content-side-closed");

        setTimeout(function () {
            fitMapBounds();
        }, 750);
    });

    $('#close-map').on("click", function () {
        $('#map-tab').removeClass("active");
        $(".divided-content").addClass("divided-content-side-closed").removeClass("divided-content-side-opened");
    });

    $('#apply').on("click", function () {
        $.fn.dataTable.reload($mainGridTable);
        clearMarkers();
        $(".divided-content").addClass("divided-content-side-closed").removeClass("divided-content-side-opened");
    })

    $('.menu-open-button').on("click", function () {
        $('.menu-open-button').toggleClass('active');

    });

    $('.filter-list-item').on("click", function () {
        var selectedValues = [];

        $(this).find('i').toggleClass('fa-check');
        $(this).toggleClass("active");

        var parent = $(this).parent().attr('id');

        $("#" + parent + " .filter-list-item.active").each(function (index) {
            selectedValues.push($(this).data("value"));
        });

        var control = $(this).parent().data('control')
        $(control).val(selectedValues);
        $(control).trigger("change");

    });

    $('.clear-filters').on("click", function () {
        if ($("#DocTypes").val()) {
            $("#DocTypes").val('');
            $("#DocTypes").trigger("change");
        }
        if ($("#Status").val()) {
            $("#Status").val('');
            $("#Status").trigger("change");
        }
        if ($("#ident").val()) {
            $("#ident").val('');
        }

        $("#Keywords").val('');
        $("#Keywords").trigger("change");
    });

    var typingTimer;
    var doneTypingInterval = 300;

    $('.search-input[name="Keywords"]').off('keyup');
    $('.search-input[name="Keywords"]').on('keyup', function () {

        if ($('.search-input[name="Keywords"]').val().length > 0 && $('.search-input[name="Keywords"]').val().length < 3)
            return;

        clearTimeout(typingTimer);
        typingTimer = setTimeout(function () { $.fn.dataTable.reload($mainGridTable); }, doneTypingInterval);
    });
};

function getWOOperRegTable(response) {

    var icon = '';
    var color = '';
    var caption = '';

    $("#popoverTable").empty();
    var trHTML = '';
    $.each(response.data, function (i, item) {

        switch (item.EventType) {
            case 'OB':
                icon = "fad fa-2x fa-play";
                color = "#7EAF3F";
                caption = globalWorkOrderLoc.operationStart;
                break;
            case 'OP':
                icon = "fad fa-2x fa-pause-circle";
                color = "goldenrod";
                caption = globalWorkOrderLoc.operationPause;
                break;
            case 'OC':
                icon = "fad fa-2x fa-play-circle";
                color = "#7EAF3F";
                caption = globalWorkOrderLoc.operationContinue;
                break;
            case 'OE':
                icon = "fad fa-2x fa-stop-circle";
                color = "#BB5534";
                caption = globalWorkOrderLoc.operationEnd;
                break;

            default:
                icon = "fa fa-clock-o";
                break;
        }

        trHTML +=
            '<tr>' +
            '   <td style="width:50px"> ' +
            '       <i class="' + icon + '" style= "color:' + color + '"></i>' +
            '   </td>' +
            '   <td style="width:200px">' +
            '       <label class="control-label">' + caption + ' </label>' +
            '       <div>' +
            '           <span style="font-size: 14px; display: inline-block; overflow:hidden; text-overflow: ellipsis;">' + item.EventTimeStr + '</span>' +
            '       </div >' +
            '   </td>' +
            '   <td style="width:300px">' +
            '       <label class="control-label">' + item.ResursID.trim() + ' </label>' +
            '       <div>' +
            '           <span style="font-size: 14px; display: inline-block; overflow:hidden; text-overflow: ellipsis;">' + item.Ident.trim() + " - " + item.Descr.trim() + '</span>' +
            '       </div >' +
            '       <span>' + item.Worker + '</span>' +
            '   </td>' +
            '</tr>';
    });
    $('#popoverTable').append(trHTML);
}

function setFiltersMobile() {
    var selDocs = $("#DocTypes option:selected").map(function () {
        return $(this).text();
    }).get().join(',');

    selDocs == "" ? selDocs = $("#DocTypes").attr("title") : selDocs;
    $("#doc-type-list").text(selDocs);

    var selStatus = $("#Status option:selected").map(function () {
        return $(this).text();
    }).get().join(',');

    selStatus == "" ? selStatus = $("#Status").attr("title") : selStatus;
    $("#status-list").text(selStatus);
}

function customModalForMobile(isMobile) {
    if (_isMobileWO) {
        $(".custom-modal-footer>div>button").addClass("btn-rounded");
        $(".custom-modal-body-content>span").addClass("h4");
        $(".custom-modal-title").css("font-size", 24);
    }
}

function isPastDate(dateString) {
    var date = moment(dateString, ["DD.MM.YYYY", "MM-DD-YYYY", "YYYY/MM/DD"]);

    var today = moment().startOf('day');
    return date.isBefore(today);
}
