var globalWorkRegParams;
var globalWorkRegLoc;
var globalWorkRegUrls;

var initialIdent;
var initialActiveItem;
var initialResurs;
var initialActiveResurs;

var holdUpSelected = false;
var selectedHoldUpId;

var scrapSelected = false;
var selectedScrapId;

var repairSelected = false;
var selectedRepairId;

function initializeWorkRegistration(localizations, urls, params) {

    globalWorkRegParams = params;
    globalWorkRegLoc = localizations;
    globalWorkRegUrls = urls;

    if ($("#Picture").val() == "") {
        $("#image").addClass('hidden');
        $("#noImage").removeClass('hidden');
    }

    setInProgressWork();
    var decPlaces = globalWorkRegParams.woExDecPlacesOper;

    $('.card-work-reg').find('input[type=number]').val(round(0, decPlaces));

    $('.card-work-reg').find('input[type=number]').blur(function () {
        $(this).val(round(Number($(this).val()), decPlaces));
    });

    $('.btn-plus-minus').click(function () {
        var control = $(this).parents("div").children(".form-control");

        if ($(this).children().hasClass("fa-plus")) {
            control.val(roundToPercision(decPlaces, Number(control.val()) + 1));
        };

        if ($(this).children().hasClass("fa-minus")) {
            if (Number(control.val()) > 0)
                control.val(roundToPercision(decPlaces, Number(control.val()) - 1));
        };

        control.trigger("blur");

    });

    if (globalWorkRegParams.isEventTypeNull === 'True') {
        $('#editMat-ident').on('change', function () {
            if (!initialIdent) {
                initialIdent = $('#Ident').val();
            }

            const ident = $('#editMat-ident').val();
            $('#Ident').val(ident);

            $('#start').hide();

            $('#confirmButton').attr('onclick', 'UpdatePosition(this)');
            $('#confirmButton').removeClass('hidden');
            $('#cancelButton').attr('onclick', 'cancelIdentChange()');
            $('#cancelButton').removeClass('hidden');
        });

        $('#editMat-resurs').on('change', function () {
            if (!initialResurs) {
                initialResurs = $('#Resurs').val();
            }

            const resurs = $('#editMat-resurs').val();
            $('#Resurs').val(resurs);

            $('#start').hide();

            $('#confirmButton').attr('onclick', 'UpdatePosition(this)');
            $('#confirmButton').removeClass('hidden');
            $('#cancelButton').attr('onclick', 'cancelIdentChange()');
            $('#cancelButton').removeClass('hidden');
        });

        if (params.isMobile === 'True') {
            $('#ident').on('click', function () {
                $('#tabCaption').text(globalWorkRegLoc.ident);
                $('#sideNavBar>.tab-pane').removeClass("active");
                $('#sideNavBar>.nav>.nav-item').removeClass("active");
                $('#sideNavBar>#ident-list').addClass("fade").addClass("in").addClass("active");

                $(".divided-content").addClass("divided-content-side-opened").removeClass("divided-content-side-closed");
            });

            $('.ident-list-item').on("click", function () {
                if (!initialIdent) {
                    initialIdent = $('#Ident').val();
                    initialActiveItem = $('.ident-list-item.active');
                }

                $('.ident-list-item').find('i').removeClass('fa-check');
                $('.ident-list-item').removeClass('active');

                $('#ident').val($(this).data("value"));
                $('#Ident').val($(this).data("value"));

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

                $('#start').hide();

                $('#confirmButton').attr('onclick', 'UpdatePosition(this)');
                $('#confirmButton').removeClass('hidden');
                $('#cancelButton').attr('onclick', 'cancelIdentChange()');
                $('#cancelButton').removeClass('hidden');
                $('.btn-close-side-panel').click();
            });

            $('#resurs').on('click', function () {
                $('#tabCaption').text(globalWorkRegLoc.resurs);
                $('#sideNavBar>.tab-pane').removeClass("active");
                $('#sideNavBar>.nav>.nav-item').removeClass("active");
                $('#sideNavBar>#resurs-list').addClass("fade").addClass("in").addClass("active");

                $(".divided-content").addClass("divided-content-side-opened").removeClass("divided-content-side-closed");
            });

            $('.resurs-list-item').on("click", function () {
                if (!initialResurs) {
                    initialResurs = $('#resurs').val();
                    initialActiveResurs = $('.resurs-list-item.active');
                }

                $('.resurs-list-item').find('i').removeClass('fa-check');
                $('.resurs-list-item').removeClass('active');

                $('#resurs').val($(this).data("value"));
                $('#Resurs').val($(this).data("value"));

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

                $('#start').hide();

                $('#confirmButton').attr('onclick', 'UpdatePosition(this)');
                $('#confirmButton').removeClass('hidden');
                $('#cancelButton').attr('onclick', 'cancelIdentChange()');
                $('#cancelButton').removeClass('hidden');
                $('.btn-close-side-panel').click();
            });
        }
    }

    $('#options').on("click", function () {
        $('#tabCaption').text(globalWorkRegLoc.additionalSettings);
        $('#sideNavBar>.tab-pane').removeClass("active");
        $('#sideNavBar>.nav>.nav-item').removeClass("active");
        $('#sideNavBar>#item-options').addClass("fade").addClass("in").addClass("active");

        $(".divided-content").addClass("divided-content-side-opened").removeClass("divided-content-side-closed");
    });

    $('.btn-back-to-menu').on("click", function () {

        $(".btn.btn-close-side-panel").toggleClass("hidden");
        $(".btn.btn-back-to-menu").toggleClass("hidden");

        $('#sideNavBar>.tab-pane').removeClass("active");
        $('#sideNavBar>.nav>.nav-item').removeClass("active");
        $('#sideNavBar>#item-options').addClass("fade").addClass("in").addClass("active");

        $(".divided-content").addClass("divided-content-side-opened").removeClass("divided-content-side-closed");

        if ($("#homeTab").hasClass("divided-tab-3"))
            $("#homeTab").removeClass("divided-tab-3").addClass("divided-tab-1 active");

        var caption = $("#homeTab>#tabCaption>span").attr("data-default-caption");           
        $("#homeTab>#tabCaption>span").text(caption);

    });

    $('#apply').on("click", function () {
        $(".divided-content").addClass("divided-content-side-closed").removeClass("divided-content-side-opened");

    });

    $('.btn-close-side-panel').on("click", function () {
        $(".divided-content").addClass("divided-content-side-closed").removeClass("divided-content-side-opened");
    });

    $('#work-history').on("click", function () {
        var caption = $("#work-history").find("h3").text();
        $("#homeTab>#tabCaption>span").text(caption);

        if ($("#homeTab").hasClass("divided-tab-1"))
            $("#homeTab").removeClass("divided-tab-1").addClass("divided-tab-3");
        

        $(".btn.btn-close-side-panel").toggleClass("hidden");
        $(".btn.btn-back-to-menu").toggleClass("hidden");


        InitWoExregOperExp();

    });

    $('#image').on("click", function () {
        $("#imageModal").modal('show');
    }).hover(function () {
        $(this).css('cursor','pointer');
    });

    $('#note').on("click", function () {
        var caption = $("#note").find("h3").text();
        $("#tabCaption>span").text(caption);

        $(".btn.btn-close-side-panel").toggleClass("hidden");
        $(".btn.btn-back-to-menu").toggleClass("hidden");

    });

    $('#operation-materials').on("click", function () {
        var caption = $("#operation-materials").find("h3").text();
        $("#tabCaption>span").text(caption);

        $(".btn.btn-close-side-panel").toggleClass("hidden");
        $(".btn.btn-back-to-menu").toggleClass("hidden");

        initializeMaterialsTab();

    });

    $('#finish-task').on("click", function () {

        if ($("#finish-task").hasClass('active')) {
            $("#finish-task").removeClass("active");
            $("#finish-task :input").prop('checked', false);

        } else {
            $("#finish-task").addClass("active");
            $("#finish-task :input").prop('checked', true);
        }


    });

    $('#confirm-receiving').on("click", function () {

        if ($("#confirm-receiving").hasClass('active')) {
            $("#confirm-receiving").removeClass("active");
            $("#confirm-receiving :input").prop('checked', false);
        } else {
            $("#confirm-receiving").addClass("active");
            $("#confirm-receiving :input").prop('checked', true);            
        }
        $("#confirm-receiving :input").trigger("change");

    });

    $('#confirmReceive').on("change", function () {

        if ($(this).prop('checked')) {
            getSerialNumbersForIdent();

            $('#finished').on('blur', function () {
                changeQty(this.id, 'K')
            });

            $('#scrap').on('blur', function () {
                changeQty(this.id, 'P')
            });
        } else {
            $('#finished').off("blur");
            $('#scrap').off("blur");
        }

    });

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

    if ($(".divided-content-toggle-open").hasClass('hidden')) {
        InitWoExregOperExp();
    } 

    $('.divided-content-toggle-open').on("click", function () {
        InitWoExregOperExp();
    });

    getSerialNumbersForIdent();

    $('#select-holdup-btn').on('click', function () {
        holdUpSelected = true;
        selectedHoldUpId = $('#selected-holdup').val();
        var text = $("#selected-holdup option:selected").text();
        $('#holdup-text').text(text)
    });

    $('#HoldUps').on('blur', function () {
        if (!holdUpSelected) {
            $('#holdup-modal').modal('show');
        }
    });

    $('#select-scrap-btn').on('click', function () {
        scrapSelected = true;
        selectedScrapId = $('#selected-scrap').val();
        var text = $("#selected-scrap option:selected").text();
        $('#scrap-text').text(text)
    });

    $('#scrap').on('blur', function () {
        if (!scrapSelected) {
            $('#scrap-modal').modal('show');
        }
    });

    $('#select-repair-btn').on('click', function () {
        repairSelected = true;
        selectedRepairId = $('#selected-repair').val();
        var text = $("#selected-repair option:selected").text();
        $('#repair-text').text(text)
    });

    $('#repair').on('blur', function () {
        if (!repairSelected) {
            $('#repair-modal').modal('show');
        }
    });

    $('#select-scrap-btn').on('click', function () {
        scrapSelected = true;
        selectedScrapId = $('#selected-scrap').val();
        var text = $("#selected-scrap option:selected").text();
        $('#scrap-text').text(text)
    });

    $('#scrap').on('blur', function () {
        if (!scrapSelected) {
            $('#scrap-modal').modal('show');
        }
    });

    $('#select-repair-btn').on('click', function () {
        repairSelected = true;
        selectedRepairId = $('#selected-repair').val();
        var text = $("#selected-repair option:selected").text();
        $('#repair-text').text(text)
    });

    $('#repair').on('blur', function () {
        if (!repairSelected) {
            $('#repair-modal').modal('show');
        }
    });
};

function startWorkRecording(button) {

    var icon = $(button).data("icon");

    if ($(button).hasClass("btn-primary")) {

        swapLoadingIcon(true, $(button).attr('id'), icon);
        $(button).attr("disabled", true);

        confirmOperationWork(true);
    }

    if ($('#Worker').val() === "") {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            id: "requiedEmployee",
            type: "alert",
            text: globalWorkRegLoc.notEmployeeText,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: globalWorkRegLoc.ok,
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
        return false;
    }

    swapLoadingIcon(true, $(button).attr('id'), icon);
    $(button).attr("disabled", true);
    
    createEvent(button, icon, true);

}

function createEvent(currentBtn, icon, isMobile) {

    var eventType = $(currentBtn).data("event-type");

    var fromDailyPlan = globalWorkRegParams.prodType === "MF" ? localStorage.getItem('WoFromDailyPlan') : "false";

    $.ajax({
        url: globalWorkRegUrls.createEvent,
        type: "POST",
        dataType: 'json',
        data: {
            AcKey: $("#AcKey").val(),
            AnNo: $("#AnNo").val(),
            Ident: $("#Ident").val(),
            Descr: $("#Descr").val(),
            UM: $("#UM").val(),
            EventType: eventType,
            EventTime: $("#EventTime").val(),
            ResursID: $("#ResursID").val(),
            Worker: $("#Worker").val(),
            ParentWorker: $("#ParentWorker").val(),
            Priority: $("#Priority").val(),
            CalendarQId: fromDailyPlan == 'true' ? $("#CalendarQId").val() : "",
            Shift: $("#Shift").val(),
            QId: $("#QId").val()
        },

        success: function (data) {
            if (!data.Success) {
                let errorText = data.Error;

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    id: "displayPopupErrorModal",
                    type: "alert",
                    text: errorText,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: globalWorkRegLoc.ok,
                            closeOnAction: true,
                            type: 'primary',
                            action: function () {
                                location.reload();
                            }
                        }
                    ]
                });
                customModalForMobile(isMobile);
                return;
            }
            
            location.reload();
            startTracking(eventType);
            swapLoadingIcon(false, currentBtnId, icon);
            $("#confirmButton").addClass('disabled');
        },
        error: function (error) {
            swapLoadingIcon(false, currentBtnId, icon);
            $("#confirmButton").removeClass('disabled');
        }
    });
}

function startTracking(eventType) {
    if (eventType === "OB") {
        $(".stopwatch").stopwatch().stopwatch('start');
    }
    if (eventType === "OP") {
        $(".stopwatch").stopwatch().stopwatch('stop');
    }
    if (eventType === "OC") {
        $(".stopwatch").stopwatch().stopwatch('start');
    }
    if (eventType === "OE") {

    }
}

function continueStopwatch(milliseconds, eventType) {
    if ((eventType === "OP") || (eventType === "OE")) {
        $('.stopwatch').stopwatch({ startTime: milliseconds }).stopwatch('render');
    }
    else {
        $('.stopwatch').stopwatch({ startTime: milliseconds }).stopwatch('start');
    }
}

function setInProgressWork() {

    var eventTypeCurrent = $("#EventType").val();

    if (eventTypeCurrent != "") {
        var button = $("a[data-event-type=" + eventTypeCurrent + "]");
        var ms = $(button).data('milliseconds');

        continueStopwatch(ms, eventTypeCurrent);
    }
    else {
        $('#doneTime').removeClass('hidden');
    }
}

function confirmOperationWork(isMobile) {

    if ($('#Worker').val() === "") {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            id: "requiedEmployee",
            type: "alert",
            text: globalWorkRegLoc.notEmployeeText,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: globalWorkRegLoc.ok,
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
        customModalForMobile(isMobile);
        return false;
    }

    if ($("#EventType").val() === "") {
        confirmOperation(isMobile);
    }
    else
        if ($("#EventType").val() === "OE") {
            confirmWorkReg(isMobile);
        }
        else {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                id: "displayPopupSuccessModal",
                type: "question",
                text: globalWorkRegLoc.questionText,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: globalWorkRegLoc.yes,
                        closeOnAction: true,
                        type: 'primary',
                        action: function () {
                            stopWorkRecordings("record-button-3");
                        }
                    },
                    {
                        icon: 'fa fa-times',
                        text: globalWorkRegLoc.no,
                        closeOnAction: true,
                        type: 'primary'
                    },

                ]
            });
            customModalForMobile(isMobile);
        }
}

function confirmWorkReg(isMobile) {

    swapLoadingIcon(true, "confirmButton", "fa fa-check");
    $("#confirmButton").addClass('disabled');

    var data = {
        AcKey: $("#AcKey").val(),
        AnNo: $("#AnNo").val(),
        Ident: $("#Ident").val(),
        Descr: $("#Descr").val(),
        UM: $("#UM").val(),
        EventType: $("#EventType").val(),
        EventTime: $("#EventTime").val(),
        ResursID: $("#ResursID").val(),
        Worker: $("#Worker").val(),
        ParentWorker: $("#ParentWorker").val(),
        Priority: $("#Priority").val(),
        CalendarQId: $("#CalendarQId").val(),
        Date: $("#Date").val(),
        Shift: $("#Shift").val(),
        QId: $("#QId").val(),
        Milliseconds: toNumber($("#UsedTime").val()) * 1000 * 60 * 60,
        GoodPcs: $("#finished").val().replace('.', ','),
        ScrapPcs: $("#scrap").val().replace('.', ','),
        ScrapId: scrapSelected ? selectedScrapId : 0,
        WastePcs: $("#waste").val().replace('.', ','),
        RepairQty: $("#repair").val().replace('.', ','),
        RepairId: repairSelected ? selectedRepairId : 0,
        HoldUps: $("#HoldUps").val().replace('.', ','),
        HoldUpId: holdUpSelected ? selectedHoldUpId : 0,
        Note: $("#Note").val(),
        Finished: $("#finishOperation").is(":checked") ? "Y" : "N",
        ConfirmReceive: $("#confirmReceive").is(":checked") ? "1" : "0",
        ProdType: globalWorkRegParams.prodType

    };

    $.post(globalWorkRegUrls.confirmOperWork, data)
        .done(function (response) {

            if (response.Success) {

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    id: "displayPopupSuccessModal",
                    type: "success",
                    text: globalWorkRegLoc.successWorkMsg,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: globalWorkRegLoc.ok,
                            closeOnAction: true,
                            type: 'primary',
                            action: function () {
                                if (data.Finished == 'Y') {
                                    location.href = "WorkOrderOperations?key=" + data.AcKey;
                                }
                                else {
                                    location.reload();
                                }
                            }
                        }
                    ]
                });
                customModalForMobile(isMobile);

            } else {

                let errorText = response.Error;

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    id: "displayPopupErrorModal",
                    type: "alert",
                    text: errorText,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: globalWorkRegLoc.ok,
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
                customModalForMobile(isMobile);
            }
            swapLoadingIcon(false, "confirmButton", "fa fa-check");
            $("#confirmButton").removeClass('disabled');
        });


}

function confirmOperation(isMobile) {

    if (toNumber($("#UsedTime").val()) === 0) {
        var requiedText = globalWorkRegLoc.requiedQty;
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            id: "requiedInput",
            type: "alert",
            text: requiedText,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: globalWorkRegLoc.ok,
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
        customModalForMobile(isMobile);
        return false;
    };

    swapLoadingIcon(true, "confirmButton", "fa fa-check");
    $("#confirmButton").addClass('disabled');

    var data = {
        AcKey: $("#AcKey").val(),
        AnNo: $("#AnNo").val(),
        Variant: $("#WoExItem_Variant").val(),
        Ident: $("#Ident").val(),
        Descr: $("#Descr").val(),
        Date: $("#Date").val(),
        UM: $("#UM").val(),
        Worker: $("#Worker").val(),
        QId: $("#WoExItem_QId").val(),
        Note: $("#Note").val(),
        ResursID: $("#ResursID").val(),
        ResourceQId: globalWorkRegParams.resourceQId,
        BeginTime: $("#BeginTime").val(),
        Time: $("#UsedTime").val().replace('.', ','),
        Tn: 0,
        Tpf: 0,
        Price: 0,
        RatifyPcs: 0,
        Qty: $("#finished").val().replace('.', ','),
        ScrapPcs: $("#scrap").val().replace('.', ','),
        ScrapId: scrapSelected ? selectedScrapId : 0,
        WastePcs: $("#waste").val().replace('.', ','),
        RepairQty: $("#repair").val().replace('.', ','),
        RepairId: repairSelected ? selectedRepairId : 0,
        HoldUp: $("#HoldUps").val().replace('.', ','),
        HoldUpId: holdUpSelected ? selectedHoldUpId : 0,
        Finished: $("#finishOperation").is(":checked") ? "Y" : "N",
        ConfirmReceive: $("#confirmReceive").is(":checked") ? "1" : "0",
        ProdType: globalWorkRegParams.prodType
    };

    $.post(globalWorkRegUrls.confirmOperation, data)
        .done(function (response) {

            if (response.Success) {

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    id: "displayPopupSuccessModal",
                    type: "success",
                    text: globalWorkRegLoc.successWorkMsg,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: globalWorkRegLoc.ok,
                            closeOnAction: true,
                            type: 'primary',
                            action: function () {
                                if (data.Finished == 'Y') {
                                    location.href = "WorkOrderOperations?key=" + data.AcKey;
                                }
                                else {
                                    location.reload();
                                }
                            }
                        }
                    ]
                });
                customModalForMobile(isMobile);

            } else {

                let errorText = response.Error;

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    id: "displayPopupErrorModal",
                    type: "alert",
                    text: errorText,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: globalWorkRegLoc.ok,
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
                customModalForMobile(isMobile);

            }
         
            swapLoadingIcon(false, "confirmButton", "fa fa-check");
            $("#confirmButton").removeClass('disabled');
        });

}

function deleteWorkReg(isMobile) {

    swapLoadingIcon(true, "cancelButton", "far fa-window-close");
    $("#confirmButton").addClass('disabled');
    $("#cancelButton").addClass('disabled');

    var data = {
        AcKey: $("#AcKey").val(),
        AnNo: $("#AnNo").val(),
        Worker: $("#Worker").val(),
        ResursID: $("#ResursID").val()
    };

    $.post(globalWorkRegUrls.deleteOperWork, data)
        .done(function (response) {

            if (response.Success) {
                location.reload();
            } else {

                let errorText = response.Error;

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    id: "displayPopupErrorModal",
                    type: "alert",
                    text: errorText,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: globalWorkRegLoc.ok,
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
                customModalForMobile(isMobile);

            }

            swapLoadingIcon(false, "cancelButton", "far fa-window-close");
            $("#cancelButton").removeClass('disabled');
            $("#confirmButton").removeClass('disabled');
        });

}

function InitWoExregOperExp(isSummary = true) {
    var decPlaces = globalWorkRegParams.woExDecPlacesOper;

    globalWorkRegParams.isSummary = isSummary;

    $dataTable = $('#woExRegOperExp');

    if ($.fn.dataTable.isDataTable('#woExRegOperExp')) {
        $.fn.dataTable.reload($dataTable);
    }
    else {
        $dataTable.DataTable({
            responsive: true,
            serverSide: false,
            scroller: false,
            responsive: true,
            paging: false,
            info: false,
            sScrollX: "100%",
            scrollX: true,
            initComplete: function () {
                $('.dataTables_scrollBody').css('max-height', '70vh');
                $('.dataTables_scrollBody').css('height', '70vh');
                $("#sh-dropdown-menu-DT").css("display", "none");
            },
            ajax: {
                url: $dataTable.attr('data-url'),
                data: function (d) {
                    d.Key = $("#AcKey").val();
                    d.No = $("#AnNo").val();
                    d.ResursID = $("#ResursID").val();
                    d.ProductionType = globalWorkRegParams.prodType;
                    d.ItemType = globalWorkRegParams.isSummary ? "S" : "D";
                }
            },
            columns: [

                { data: "Worker", name: "Worker" },
                {
                    data: "DateStr", name: "DateStr",
                    render: function (data, type, full) {
                        return data + " " + full.BeginTimeStr
                    }
                },
                { data: "TimeStr", name: "TimeStr", className: "dt-body-center" },

                {
                    name: "StatePcs",
                    render: function (data, type, full) {
                        return '<div style="min-width:max-content" ><span class="label-success m-r-sm" style="padding:5px; border-radius:10px"><i class="fas fa-thumbs-up m-r-sm"></i>' + round(full.GoodPcs, decPlaces).toString().replace('.', ',') + '</span>' +
                            '<span class="label-primary m-r-sm" style="padding:5px; border-radius:10px"><i class="fas fa-wrench m-r-sm"></i>' + round(full.RepairQty, decPlaces).toString().replace('.', ',') + '</span>' +
                            '<span class="label-danger" style="padding:5px; border-radius:10px"><i class="fas fa-times m-r-sm"></i>' + round(full.ScrapPcs, decPlaces).toString().replace('.', ',') + '</span> </div>';
                    }
                },
                {
                    data: "Note", name: "Note",
                    render: function (data, type, full) {
                        var noteClass = data === "" ? " transparent-color" : "theme-color";
                        return type === 'display' ?
                            '<button type="button" class="btn btn-link m-r-sm" data-note="' + data + '" onclick="openWoExOperRegExpNoteModal(this)">' +
                            '<i class="fa fa-comment description-hidden-icon ' + noteClass + '" ></i>' +
                            '</button >' : data;
                    }
                }
               
            ]
        });
       
    }

}

function initializeMaterialsTab() {
   
    $itemsTable = $('#mainGridMaterials');
    var itemsTable = $itemsTable.DataTable({
        initComplete: function () {
            $('.dataTables_scrollBody').css('max-height', '100vh');
            $('.dataTables_scrollBody').css('height', '100vh');

        },
        ajax: {
            url: $itemsTable.attr('data-url'),
            data: function (d) {
                d.Key = $("#AcKey").val();
                d.No = $("#AnNo").val();
                d.ItemType = "";
            }
        },
        columns: [
            {
                class: 'border-bottom',
                data: function (data) {
                    var image = data.Picture !== '' ? " <img style='max-width:100%' src='" + data.Picture + "' />" : "<i class='fal fa-image fa-3x text-muted' style='opacity:0.5'></i>";
                    return "<span style='width:100rem;position: relative;text-align: center;vertical-align: middle;display: table-cell;height: 150px;'>" + image + "</span>";
                },
                orderable: false,
                render: function (data) {
                    return data;
                }
            },

            {
                data: "IdentDescr",
                name: "IdentDescr",
                filtertype: "text",
                className: "dt-body-left",
                render: function (data, type, full) {
                    return type === 'display' ?
                        '    <span data-toggle="tooltip"  class="card-caption"  data-original-title="' + data + '" >' + data + '</span>' : data;

                }
            },
            {
                data: "AnNo",
                name: "AnNo",
                filtertype: "text",
                className: "dt-body-left",
                render: function (data, type, full) {
                    return type === 'display' ?
                        '<span style="margin-right:2px"> <i class="fa fa-hashtag"></i> </span> <span>' + data + '</span>' : data;
                }
            },
            {
                data: 'CompletedPrcQty',
                render: function (data, type, full) {
                    var color = data >= 100 ? "bg-c-green" : "bg-c-yellow"
                    var value = data > 100 ? 100 : data
                    return type === 'display' ?
                        '<div class="progress-card">' +
                        '<div class="progress">' +
                        '    <div class="progress-bar ' + color + '" style="width:' + value + '%" aria-valuenow="' + data + '" aria-valuemin="0" aria-valuemax="100"></div>' +
                        '</div>' +
                        '</div>' +
                        '<span>' + full.Status + ' (' + round(full.CompletedPrcQty, 2).toString().replace('.', ',') + '%)</span>' +
                        '<span class="pull-right">' + round(full.DonePcs, 2).toString().replace('.', ',') + '/' + round(full.PlanPcs, 2).toString().replace('.', ',') + ' ' + full.UM + '</span>' : data;

                }
            }

        ],
        createdRow: function (row, data, dataIndex) {
            $(row).css('cursor', 'pointer');
        },
        drawCallback: function () {
            $("[data-toggle='tooltip']").tooltip({
                container: 'body'
            });
        }
    }).on('click', 'tr', function () {
        var data = itemsTable.row($(this)).data();
        window.location.href = "IssuingMaterial?key=" + data.AcKey + '&no=' + data.AnNo;
    });


};

function editTime(e) {
    element.innerHTML = '<input class="required" type="text" inputmode="none" name="time" value="00:00" style="font-size: 18px;width:80px"  onblur="spanReset(this)"  data-last-value="' + $(e).text() + '" /> ';
    $('[name="time"]').datetimepicker({
        format: 'HH:mm'
    });

    $('[name="time"]').focus();

}

function spanReset(e) {

    let value = e.value;
    let timePrev = $(e).attr("data-last-value");
    let element = document.getElementById('element');

    var seconds = moment.duration(value).asSeconds()
    $("#UsedTime").val(seconds / 3600);

    var seconds = moment.duration(value).asSeconds()
    $("#UsedTime").val(seconds / 3600);

    if (seconds === 0) {
        value = timePrev;
        $("#start").removeClass("hidden");
        $("#confirmButton").addClass("hidden");
        $("#cancelButton").addClass("hidden");
    }
    else {
        $("#start").addClass("hidden");
        $("#confirmButton").removeClass("hidden");
        $("#cancelButton").removeClass("hidden");
    }

    element.innerHTML = "<span id='doneTime' style='font-size: 18px' class='@(!Model.EventType.IsEmpty() ? 'hidden' : String.Empty) ' onclick = 'editTime(this)' >" + value + "</span >";

}

function openWoExOperRegExpNoteModal(button) {
    $("#modalSave").addClass("hidden");
    $("#modalClose").removeClass("hidden");

    $("#modalNote").text($(button).data("note"));
    $('#note-modal').modal('show');
}

function UpdatePosition(button) {
    var buttonId = $(button).attr('id');
    var formData = $("#workRegistrationForm").serializeArray();

    $.each(formData, function () {
        if (!isNaN(this.value)) {
            this.value = this.value.replace('.', ',');
        }
    });
    swapLoadingIcon(true, buttonId, "fa fa-check");

    $.ajax({
        cache: false,
        type: "POST",
        url: globalWorkRegUrls.updatePosition,
        data: formData,
        success: function (response) {
            if (response.success) {
                location.reload();
            }
            else {
                response.message = response.message.replace(/\\n/g, "<br>");

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: false,
                    type: "alert",
                    text: response.message,
                    closeOtherModals: false,
                    buttons: [
                        {
                            text: globalWorkRegLoc.ok,
                            icon: 'fa fa-check',
                            closeOnAction: true,
                            type: 'primary'
                        },
                    ]
                });
            }

            swapLoadingIcon(false, buttonId, "fa fa-check");
        },
        error: function (error) {
            console.error(error);

            swapLoadingIcon(false, buttonId, "fa fa-check");
        }
    });
}

function cancelIdentChange() {
    if (initialIdent) {
        $('#Ident').val(initialIdent);
        $('#ident').val(initialIdent);
        $('#editMat-ident').val(initialIdent);
        $('#editMat-ident').selectpicker('refresh');
    }
    if (initialActiveItem) {
        $('.ident-list-item').find('i').removeClass('fa-check');
        $('.ident-list-item').removeClass('active');
        initialActiveItem.find('i').addClass('fa-check');
        initialActiveItem.addClass('active');
    }

    if (initialResurs) {
        $('#Resurs').val(initialResurs);
        $('#resurs').val(initialResurs);
        $('#editMat-resurs').val(initialResurs);
        $('#editMat-resurs').selectpicker('refresh');
    }
    if (initialActiveResurs) {
        $('.resurs-list-item').find('i').removeClass('fa-check');
        $('.resurs-list-item').removeClass('active');
        initialActiveResurs.find('i').addClass('fa-check');
        initialActiveResurs.addClass('active');
    }

    $('#start').show();
    $('#confirmButton').addClass('hidden');
    $('#confirmButton').attr('onclick', 'confirmOperationWork(true)');
    $('#cancelButton').addClass('hidden');
    $('#cancelButton').attr('onclick', 'deleteWorkReg(true)');

    initialIdent = null;
    initialActiveItem = null;
    initialResurs = null;
    initialActiveResurs = null;
}
