var distanceTableData;
var editedPNTable;
var latestEdit = "DistancesTable-0";

$(document).ready(function () {
    getTableConfigurationPN().done(function () {
        setDropdownMenuPN();
        hideColumnsPN();
        focusSelect2PN();
    });

    $(".destination-table").on("click", function () {
        var sectionToColapse = $(this).next().attr("id");
        $('#' + sectionToColapse).on('shown.bs.collapse', function () {
            resizableGridPN($(".distance-PN")[sectionToColapse.slice(-1)]);
        });
    });
});

$(window).on("beforeunload", function () {
    if (editedPNTable) {
        saveTableConfigurationPN();
    }
});

function getTableConfigurationPN() {

    return $.ajax({
        url: $("#GetTableGrid").val(),
        data: {
            TableName: "travel-orders"
        },
        success: function (data) {
            if (!jQuery.isEmptyObject(data)) {
                distanceTableData = data;
                reorderColumnsPN();
                resizeTablePN();
            }
            checkForObligations();
        }
    });
}

function saveTableConfigurationPN() {
    let columns = [];
    let column = {};
    var tableName = "travel-orders";

    $("#" + latestEdit + " > tbody > tr > td").each(function () {
        var columnId = $(this).data("column-id");
        var position = $(".distance-PN > tbody > tr > td[data-column-id='" + columnId + "']").index();
        var isHidden = $(this).hasClass("hidden-column");
        var width = $(this).innerWidth();

        column = {
            Id: columnId,
            Position: position,
            IsHidden: isHidden,
            Width: width
        };
        columns.push(column);
    });

    $.ajax({
        url: $("#SaveTableGrid").val(),
        method: 'POST',
        data: {
            TableName: tableName,
            Columns: columns
        },
        success: function () {
        }
    });
}

function setDropdownMenuPN() {
    var tableDistance = $(".destination-table > tbody > tr");
    var showHideColumnsTitle = $("#ShowHideColumns").val();
    var dropdownMenu = `<span class="showHideDropdown" title="${showHideColumnsTitle}">
            <a role='button' class='pull-right'>
                <span class='default-icon-color'>   
                    <i class='fas fa-ellipsis-v'></i>
                </span>
            </a>
            <ul class='dropdown-menu sh-dropdown-position' id='show-hide-list'></ul>
        </span>`;

    tableDistance.append(dropdownMenu);
    populateDropdownPN();
    openCloseDropdownPN();
}

function populateDropdownPN() {
    $("#DistancesTable-0 > tbody > tr > td").each(function (index) {
        var text = $(this).find("div > label").text().trim();
        var columnId = $(this).data("column-id");
        var defaultHidden = $(this).data("default-hidden");

        if (isRequired(columnId)) return;
        
        if (distanceTableData && distanceTableData.TableName != null) {
            var columnData = distanceTableData.Columns.filter(el => { return el.Id === columnId })[0];
        }

        if (columnData != null && columnData.IsHidden) {
            isChecked = 0;
            $(this).addClass("hidden-column");
        } else {
            var isChecked = 1;
        }

        if (!columnData && defaultHidden === true) {
            isChecked = 0;
            $(this).addClass("hidden-column");
        }

        var hasClassHidden = $(this).hasClass("hidden");
        var hidden = text == "" || text == null || index == 0 || index == 1 || index == 2 || hasClassHidden ? "hidden" : "";

         var listItem = `
                <li class='${hidden}'>
                    <label class="custom-checkbox-container">
                        <input type='checkbox' data-column='${index}' name='PREF${columnId}' class='custom-checkbox sh-checkbox' ${isChecked ? 'checked' : ''} />
                        ${text}
                        <span class="custom-checkbox-checkmark"></span>
                    </label>
                </li>`;

        $(".sh-dropdown-position").append(listItem);
    });
}

function hideColumnsPN() {
    $(".distance-PN > tbody > tr > td").each(function () {
        var columnId = $(this).data("column-id");

        if (distanceTableData && distanceTableData.TableName != null) {
            var columnData = distanceTableData.Columns.filter(el => { return el.Id === columnId })[0];
        }

        if (columnData != null && columnData.IsHidden && !isRequired(columnId)) {
            $(this).addClass("hidden-column");
        }
    });
}

function openCloseDropdownPN() {
    var mobile = isMobile();
    var tablet = isTablet();

    $('.showHideDropdown a').on('click', function (event) {
        let dropdown = $(this).parent();
        if (dropdown.hasClass('open')) {
            dropdown.removeClass('open');
            return;
        }
        $('.showHideDropdown').removeClass('open');
        dropdown.addClass('open');
        if (!mobile && !tablet) {
            $('.divided-content-scrollable').css({
                "overflow-y": "unset",
                "overflow-x": "unset"
            });
        }
    });

    $('body').on('click', function (e) {
        if (!$('.showHideDropdown').is(e.target)
            && $('.showHideDropdown').has(e.target).length === 0
            && $('.open').has(e.target).length === 0
        ) {
            $('.showHideDropdown').each(function (index) {
                $(this).removeClass('open');
            });
        }
    });
}

$(document).on('click', '.sh-checkbox', function () {
    var checked = $(this).is(":checked");
    var chechkboxName = $(this).attr("name");
    var columnId = chechkboxName.slice(4);
    var th = $('tbody > tr > td[data-column-id="' + columnId + '"]');
    editedPNTable = true;

    if (checked) {
        $('[name="' + chechkboxName + '"]').prop('checked', true);
        th.removeClass("hidden-column");
        th.attr("visible", true);
    } else {
        $('[name="' + chechkboxName + '"]').prop('checked', false);
        th.addClass("hidden-column");
        th.attr("visible", false);
    }

    saveTableConfigurationPN();
});

$(function () {
    if (screen.width > 768) {
        $('.distance-PN > tbody > tr').sortable({
            cursor: "move",
            placeholder: "ui-state-highlight",
            opacity: 0.7,
            helper: "clone",
            axis: 'x',
            items: 'td:not([data-sortable])',
            start: function (e, ui) {
                var ind_th = ui.item.index();
                $('.distance-PN > tbody > tr').each(function (ind, el) {
                    $('td', el).eq(ind_th).addClass('drg');
                });
            },
            stop: function (e, ui) {
                var itInd = ui.item.index();
                $(".distance-PN > tbody > tr").each(function (ind, el) {
                    var cell = $(".drg", el).detach();
                    if (itInd >= $("td", el).length) {
                        cell.appendTo($(el));
                    } else {
                        cell.insertBefore($("td", el).eq(itInd));
                    }
                    cell.removeClass("drg");
                });
                editedPNTable = true;
            }
        }).disableSelection();
    }
});

function reorderColumnsPN() {
    var colOrder = {};
    var distanceTables = $("#distance-accordion .destination-table");

    $(".distance-PN > tbody > tr > td").each(function (i) {
        var columnId = $(this).data("column-id");
        var columnData = distanceTableData.Columns.filter(el => { return el.Id === columnId })[0];
        if (columnData) {
            colOrder[i] = columnData.Position;
        }
    });

    for (var i = 0; i < distanceTables.length; i++) {
        $("#distance-accordion-" + i).find(".purposeDropdown select").select2("destroy");
        $("#distance-accordion-" + i).find(".costDrvDropdown select").select2("destroy");
        $("#distance-accordion-" + i).find(".departmentDropdown select").select2("destroy");
    }

    $(".distance-PN > tbody > tr").html(function (i) {
        return $(this).children().sort(function (a, b) {
            var aOrder = colOrder[$(a).index()],
                bOrder = colOrder[$(b).index()];
            return aOrder - bOrder;
        });
    });

    select2withAPI();
    initializeDateTimePicker();
    showDistanceDateTimePicker();
}

function resizeTablePN() {
    var colOrder = {};
    $(".distance-PN > tbody > tr > td").each(function (i) {
        var columnId = $(this).data("column-id");
        var columnData = distanceTableData.Columns.filter(el => { return el.Id === columnId })[0];
        if (columnData) {
            colOrder[i] = columnData.Position;
        }

        $(this).innerWidth(columnData.Width);
    });
}

$(function () {
    for (var i = 0; i < $(".distance-PN").length; i++) {
        resizableGridPN($(".distance-PN")[i]);
    }
});

function resizableGridPN(table) {
    var row = table.getElementsByTagName('tr')[0],
        cols = row ? row.children : undefined;
    if (!cols) return;
    var tableHeight = table.offsetHeight;

    for (var i = 0; i < cols.length; i++) {
        var div = createDiv(tableHeight);
        cols[i].appendChild(div);
        cols[i].style.position = 'relative';
        setListeners(div);
    }

    function setListeners(div) {
        if (screen.width > 768) {
            var pageX, curCol, nxtCol, curColWidth, nxtColWidth;

            div.addEventListener('mousedown', function (e) {
                $('.distance-PN > tbody > tr').sortable('disable');
                editedPNTable = true;
                curCol = e.target.parentElement;
                nxtCol = curCol.nextElementSibling;
                pageX = e.pageX;

                latestEdit = $(curCol).closest("table").attr("id");

                var padding = paddingDiff(curCol);

                curColWidth = curCol.offsetWidth - padding;
                if (nxtCol)
                    nxtColWidth = nxtCol.offsetWidth - padding;
            });

            div.addEventListener('mouseover', function (e) {
                e.target.style.borderRight = '1px solid gray';
            })

            div.addEventListener('mouseout', function (e) {
                e.target.style.borderRight = '';
            })

            document.addEventListener('mousemove', function (e) {
                if (curCol) {
                    var diffX = e.pageX - pageX;

                    if (nxtCol)
                        nxtCol.style.width = (nxtColWidth - (diffX)) + 'px';

                    curCol.style.width = (curColWidth + diffX) + 'px';
                }
            });

            document.addEventListener('mouseup', function (e) {
                curCol = undefined;
                nxtCol = undefined;
                pageX = undefined;
                nxtColWidth = undefined;
                curColWidth = undefined
                $('.distance-PN > tbody > tr').sortable("option", "disabled", false);
            });
        }
    }

    function createDiv(height) {
        var div = document.createElement('div');
        div.style.top = 0;
        div.style.right = 0;
        div.style.width = '5px';
        div.style.position = 'absolute';
        div.style.cursor = 'col-resize';
        div.style.userSelect = 'none';
        div.style.height = height + 'px';
        return div;
    }

    function paddingDiff(col) {

        if (getStyleVal(col, 'box-sizing') == 'border-box') {
            return 0;
        }

        var padLeft = getStyleVal(col, 'padding-left');
        var padRight = getStyleVal(col, 'padding-right');
        return (parseInt(padLeft) + parseInt(padRight));
    }

    function getStyleVal(elm, css) {
        return (window.getComputedStyle(elm, null).getPropertyValue(css));
    }
};

function focusSelect2PN() {
    if (!$('#travel-orders-iris').hasClass('in')) {
        searchOnFocus();

        if (window.location.pathname.includes("Create") && $("#HeaderWorker")[0].innerText === "") {
            $("#HeaderWorker").select2('open').next().find(".select2-selection--single").focus();
        } else {
            //$('#NewNode').focus();
        }
    }
}

function checkForObligations() {
    var canDocTypeWrite = paw.utils.value.strToBool($('#CanDocTypeWrite').val());
    if (!canDocTypeWrite) {
        return;
    }

    var isObligDept = $("#IsObligDept").val();
    var isObligCostDrv = $("#IsObligCostDrv").val();
    var isObligCostDrvEmpty = true;
    var isObligDeptEmpty = true;

    if ($("#DistancesCount").val() > 0) {
        var numOfDistances = $('#distance-accordion > div:visible').length;
        var numOfSelectedCostDrvs = $(".costDrvDropdown .select2-selection__clear").length; 
        var numOfSelectedDepts = $(".departmentDropdown .select2-selection__clear").length;

        numOfSelectedCostDrvs == numOfDistances ? isObligCostDrvEmpty = false : isObligCostDrvEmpty = true;
        numOfSelectedDepts == numOfDistances ? isObligDeptEmpty = false : isObligDeptEmpty = true;

        if (isObligDept == "True" && isObligDeptEmpty) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "error",
                text: $("#MustEnterDepartment").val(),
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#Confirm").val(),
                        closeOnAction: true,
                        type: 'primary',
                        action: function () { openAccordions(".departmentDropdown") }
                    }
                ],
            });
            return;
        }

        if (isObligCostDrv == "True" && isObligCostDrvEmpty) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "error",
                text: $("#CostDrvError").val(),
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#Confirm").val(),
                        closeOnAction: true,
                        type: 'primary',
                        action: function () { openAccordions(".costDrvDropdown") }
                    }
                ],
            });
            return;
        }
    }
}

function openAccordions(elementClass) {
    let accordions = $("#distance-accordion").children();
    accordions.each(function (i) {
        let dropdown = $(this).find(elementClass);
        let dropdownValue = dropdown.children("select").val();

        if (dropdownValue == "") {
            if (!$("#collapse-" + i).hasClass("in")) {
                $(this).find("#heading-" + i).click();
            }

            setTimeout(() => {
                var wrapper = document.getElementById('mobile-wrapper-scrollable');
                wrapper.scrollTop = dropdown.offset().top;
                dropdown.children("select").select2('focus');
            }, "300");
        }
    });
}

function isRequired(c) {
    let columnElement = $('[data-column-id="' + c + '"]');
    return columnElement.hasClass('isRequired');
}