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;
    globalWorkRegParams.isMobile = globalWorkRegParams.isMobile == 'True' ? true : false;

    if (globalWorkRegParams.isMobile)
        $('.document-list-no-footer').css("margin-bottom", "150px");

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

    setInProgressWork($("#EventType").val());
    var decPlaces = globalWorkRegParams.woExDecPlacesOper;
    $('.btn-plus-minus').click(function () {
        var control = $(this).parents("div").children(".form-control");

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

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

        calcTimeFromQty();
    });

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

            const ident = $('#editOper-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) {
            $('#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();
            });            
        }
    }

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

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

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

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

            $('#mWorker').val($(this).data("value"));
            $('#Worker').val($(this).data("value"));

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

            $('.btn-close-side-panel').click();
        });

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

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

        $('.scrap-list-item').on("click", function () {

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

            $('#scrap-reason').val($(this).data("display"));
            $('#selected-scrap').val($(this).data("value"));

            $(this).find('i').toggleClass('fa-check');
            $(this).addClass("active");
            $('#selected-scrap').trigger("change");

            $('#tabCaption').text(globalWorkRegLoc.scrapCaption + " & " + globalWorkRegLoc.repairCaption);
            $('#sideNavBar>.tab-pane').removeClass("active");
            $('#sideNavBar>.nav>.nav-item').removeClass("active");
            $('#sideNavBar>#scrap-reasons').addClass("fade").addClass("in").addClass("active");

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

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

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

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

        $('.holdup-list-item').on("click", function () {

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

            $('#holdup-reason').val($(this).data("display"));
            $('#selected-holdup').val($(this).data("value"));

            $(this).find('i').toggleClass('fa-check');
            $(this).addClass("active");
            $('#selected-holdup').trigger("change");

            $('#tabCaption').text(globalWorkRegLoc.holdupCaption);
            $('#sideNavBar>.tab-pane').removeClass("active");
            $('#sideNavBar>.nav>.nav-item').removeClass("active");
            $('#sideNavBar>#holdUp-reasons').addClass("fade").addClass("in").addClass("active");

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

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

    }

    $('#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");

        $("#homeTab").children("#tabCaption").text($("#homeTab").children("#tabCaption").attr("data-default-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 () {
        $("#homeTab").children("#tabCaption").text($("#work-history").find("h3").text());

        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 () {
        $("#homeTab").children("#tabCaption").text($("#note").find("h3").text());

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

    $('#operation-materials').on("click", function () {
        $("#homeTab").children("#tabCaption").text($("#operation-materials").find("h3").text());

        $(".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").prop('checked', function () {

        if (localStorage.getItem('confirmReceive') === "true") {
            $('#serial-btn').removeClass('hidden');
            $('#scrap-serial-btn').removeClass('hidden');
            $('#repair-serial-btn').removeClass('hidden');

            getSerialNumbersForIdent();
        }
        else {
            $('#serial-btn').addClass('hidden');
            $('#scrap-serial-btn').addClass('hidden');
            $('#repair-serial-btn').addClass('hidden');
        }

        return localStorage.getItem('confirmReceive') === "true";
    });

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

        localStorage.setItem('confirmReceive', this.checked);

        if ($(this).prop('checked')) {
            $('#serial-btn').removeClass('hidden');
            $('#scrap-serial-btn').removeClass('hidden');
            $('#repair-serial-btn').removeClass('hidden');
            getSerialNumbersForIdent();

        } else {
            $('#serial-btn').addClass('hidden');
            $('#scrap-serial-btn').addClass('hidden');
            $('#repair-serial-btn').addClass('hidden');
        }

    });

    $(".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();
    });

    $("#Worker").off("change.tableReload");
    $("#Worker").on("change.tableReload", function (e) {
        $("#Worker").val($("#Worker option:selected").val());
        createEvent(this);
        $('#closeBtn').trigger('click')
    });

    $(".serialNo-btn").on('click', function (e) {
        var controlId = $(this).attr("data-input-contol");
        var control = $('#' + controlId)
        updateQty = false;

        e.preventDefault();
        changeQty(control)
        updateQty = true;
    });

    $(".serialNo-Input").on('keydown', function (e) {
        var controlId = $(this).attr("data-btn-contol");
        
        if ($(this).val() > 0  && (e.keyCode === 13 || e.key === 'Enter')) {
            calcTimeFromQty();
            if ($("#confirmReceive").prop('checked')) {
                e.preventDefault();            
                $('#' + controlId).trigger('click');
            }
        }
    });

    $('#scrapPcs, #repairPcs').on("click", function () {

        if ($("#EventType").val() === "OE") {

            $('#scrapTab>a>span').text(globalWorkRegLoc.scrapCaption + " & " + globalWorkRegLoc.repairCaption);
            $('#sideNavBar>.tab-pane').removeClass("active");
            $('#sideNavBar>.nav>.nav-item').removeClass("active");
            $('#sideNavBar>#scrap-reasons').addClass("fade in active");
            $('#tabNav>li').addClass("hidden");
            $("#scrapTab").removeClass("hidden").addClass("active");
            $(".divided-content").addClass("divided-content-side-opened").removeClass("divided-content-side-closed");

            getWoExRegOperScraps(0);
        }
    });

    $('#holdUpQty').on("click", function () {

        if ($("#EventType").val() === "OE") {

            $('#scrapTab>a>span').text(globalWorkRegLoc.holdupCaption);
            $('#sideNavBar>.tab-pane').removeClass("active");
            $('#sideNavBar>.nav>.nav-item').removeClass("active");
            $('#sideNavBar>#holdUp-reasons').addClass("fade in active");
            $('#tabNav>li').addClass("hidden");
            $("#scrapTab").removeClass("hidden").addClass("active");
            $(".divided-content").addClass("divided-content-side-opened").removeClass("divided-content-side-closed");

            getWoExRegOperHoldUps(0);
        }
    });

    $('#closeBtn').on("click", function () {
        $('#sideNavBar>#work-reg-history').addClass("fade in active");
        $('#tabNav>li').addClass("hidden");
        $("#homeTab, #detailTab, #summaryTab").removeClass("hidden");
        $("#homeTab").addClass("active");
        $('#sideNavBar>#scrap-reasons').removeClass("fade in active");
        $('#sideNavBar>#holdUp-reasons').removeClass("fade in active");
        $("#homeTab").children("#tabCaption").text($("#work-history").find("h3").text());

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

};

function startWorkRecording(button) {

    var icon = $(button).find("i").attr("class");

    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);

}

function createEvent(button) {

    var eventType = $(button).data("event-type");
    var buttonId = $(button).attr('id');
    var fromDailyPlan = globalWorkRegParams.prodType === "MF" ? localStorage.getItem('WoFromDailyPlan') : "false";

    $.ajax({
        cache: false,
        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() ? $("#ResursID").val() : "",
            Worker: $("#Worker").val(),
            GoodPcs: $("#goodPcs").val().replace('.', ','),
            ScrapPcs: $("#scrapPcs").val().replace('.', ','),
            WastePcs: $("#wastePcs").val().replace('.', ','),
            RepairQty: $("#repairPcs").val().replace('.', ','),
            HoldUps: $("#holdUpQty").val().replace('.', ','),
            CalendarQId: fromDailyPlan == 'true' ? $("#CalendarQId").val() : "",
            Shift: $("#Shift").val(),
            QId: $("#QId").val()
        },
        success: function (result) { 

            $("#EventType").val(result.EventType);
            $("#Milliseconds").val(result.Milliseconds);
            $("#UsedTime").val(result.UsedTime);
            $("#goodPcs").val(result.GoodPcs);
            $("#scrapPcs").val(result.ScrapPcs);
            $("#repairPcs").val(result.RepairQty);
            $("#holdUpQty").val(result.HoldUps);
            $("#QId").val(result.QId)
            $("#stopwatch-card h3:first-child").css("color", result.Color);
            $("#stopwatch-card i:first-child").css("color", result.Color).attr("class", result.Icon);

            ShowActionButtons(result.EventType);
            setInProgressWork(result.EventType);
            swapLoadingIcon(false, buttonId, result.Icon);
            $(button).attr("disabled", false);
        },
        error: function (error) {
            swapLoadingIcon(false, buttonId, result.Icon);
            $(button).attr("disabled", false);
        }
    });
}

function continueStopwatch(milliseconds, eventType) {

    $('#stopwatch').remove();
    $('#stopwatch-div').append('<span style="font-size: 18px" id="stopwatch" class="stopwatch">00:00:00</span>');

    if ((eventType === "OP") || (eventType === "OE") || (eventType === "OW")) {

        $('#stopwatch').unbind('tick.stopwatch');
        $('#stopwatch').stopwatch({ startTime: milliseconds }).stopwatch('render');
        $('#stopwatch').stopwatch({ startTime: milliseconds }).stopwatch('stop');
        $("#progress-bar").attr("class", "progress-bar");

        switch (eventType) {
            case "OE": $("#progress-bar").removeClass("bg-c-yellow").addClass("bg-c-red"); break;
            default: $("#progress-bar").addClass("bg-c-yellow")
        }

    }
    else {

        $('#stopwatch')
            .stopwatch({ startTime: milliseconds })
            .bind('tick.stopwatch', function (e, elapsed) {

                let remainingTime = parseFloat($("#RemainingTime").val().replace(",", "."));
                remainingTime = remainingTime * 3600 * 1000;

                var _progressValue = elapsed > remainingTime ? 100 : (elapsed / remainingTime) * 100;
                var _progressPerc = _progressValue.toFixed(2) + "%";

                $("#progress-bar").css("width", _progressPerc);
                $("#progress-bar").attr("aria-valuenow", _progressValue);
                $("#progress-bar").attr("title", _progressPerc);
                $("#progress-bar").removeClass("bg-c-red").removeClass("bg-c-yellow").addClass("bg-c-green");
                _progressValue > 100 ? $("#progress-bar").removeClass("bg-c-green").addClass("bg-c-red") : $("#progress-bar").removeClass("bg-c-red").addClass("bg-c-green");

            }).stopwatch('start');
    }
}

function setInProgressWork(eventType) {

    let usedTime = toNumber($("#UsedTime").val());
    let remainingTime = toNumber($("#RemainingTime").val());
    let doneTime = toNumber($("#DoneTime").val());
    let planTime = toNumber($("#PlanTime").val());

    let _progressValue = toNumber($("#ProgressValue").val());
    let _progressPerc = toNumber($("#ProgressStr").val());

    if (eventType != "") {

        _progressValue = usedTime > remainingTime ? 100 : (usedTime / remainingTime) * 100;
        _progressPerc = _progressValue.toFixed(2) + "%";

        $('#planTime').html('/' + $("#RemainingTimeStr").val());
        $('#doneTime').addClass('hidden');
        $('#stopwatch').removeClass('hidden');
        if (!globalWorkRegParams.isMobile) {
            $('#editOper-ident-div').parent().parent().addClass('document-head-disabled-input');
            $('#editOper-ident-div').addClass('hidden');
            $('#ident').removeClass('hidden');

            $('#editOper-resurs-div').parent().parent().addClass('document-head-disabled-input');
            $('#editOper-resurs-div').addClass('hidden');
            $('#resurs').removeClass('hidden');
        }

        continueStopwatch(parseInt($("#Milliseconds").val(), 0), eventType);
    }
    else {

        $('#doneTime').removeClass('hidden');
        $('#stopwatch').addClass('hidden');
        $('#stopwatch').unbind('tick.stopwatch');
        
        if (!globalWorkRegParams.isMobile) {
            if (doneTime > 0) {
                $('#editOper-ident-div').addClass('hidden');
                $('#ident').removeClass('hidden');
                $('#editOper-resurs-div').addClass('hidden');
                $('#resurs').removeClass('hidden');
            }
            else {
                $('#editOper-ident-div').parent().parent().removeClass('document-head-disabled-input');
                $('#editOper-ident-div').removeClass('document-head-select');
                $('#editOper-ident-div').removeClass('hidden');
                $('#ident').addClass('hidden');

                $('#editOper-resurs-div').parent().parent().removeClass('document-head-disabled-input');
                $('#editOper-resurs-div').removeClass('document-head-select');
                $('#editOper-resurs-div').removeClass('hidden');
                $('#resurs').addClass('hidden');
            }
        }
    }

    if (globalWorkRegParams.prodType == 'MF') {
        $('#editOper-resurs-div').parent().parent().removeClass('hidden');
    }

    $("#progress-bar").css("width", _progressPerc);
    $("#progress-bar").attr("aria-valuenow", _progressValue);
    $("#progress-bar").attr("title", _progressPerc);

    _progressValue > 100 ?? $("#progress-bar").removeClass("bg-c-green").addClass("bg-c-red");
}

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(globalWorkRegParams.isMobile);
        return false;
    }

    if ($("#confirmReceive").is(":checked") == true) {
        if (!validationReceivingData(isMobile)) return;
    }

    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($("#Milliseconds").val()),
        GoodPcs: $("#goodPcs").val().replace('.', ','),
        ScrapPcs: $("#scrapPcs").val().replace('.', ','),
        ScrapId: $('#selected-scrap').val(),
        WastePcs: $("#wastePcs").val().replace('.', ','),
        RepairQty: $("#repairPcs").val().replace('.', ','),
        RepairId: $('#selected-repair').val(),
        HoldUps: $("#holdUpQty").val().replace('.', ','),
        HoldUpId: $('#selected-holdup').val(),
        Note: $("#Note").val(),
        Finished: $("#finishOperation").is(":checked") ? "Y" : "N",
        ConfirmReceive: $("#confirmReceive").is(":checked") ? "1" : "0",
        ProdType: globalWorkRegParams.prodType

    };

    $.post(globalWorkRegUrls.confirmWoExRegOperExp, 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(globalWorkRegParams.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(globalWorkRegParams.isMobile);
            }
            swapLoadingIcon(false, "confirmButton", "fa fa-check");
            $("#confirmButton").removeClass('disabled');
        });
}
function validationReceivingData(isMobile) {
    var goodPcs = Number($("#goodPcs").val());
    var scrapPcs = Number($("#scrapPcs").val());
    var repairPcs = Number($("#repairPcs").val());
    var wastePcs = Number($("#wastePcs").val());
    var holdUpQty = Number($("#holdUpQty").val());

    if ($("#serialNo").val() == "True") {

        if (goodPcs != sumIssuedQtyK) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: false,
                id: "requiedInput",
                type: "alert",
                text: globalWorkRegLoc.serialNumberNotEquals,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: globalWorkRegLoc.ok,
                        closeOnAction: true,
                        type: 'primary',
                        action: function () {
                            updateQty = false;
                            changeQty($('#goodPcs'));
                            updateQty = true;
                        }
                    }
                ]
            });
            customModalForMobile(isMobile);
            return false;
        }
    };

    if ($("#scrapSerialNo").val() == "True") {

        if (scrapPcs != sumIssuedQtyP || repairPcs != sumIssuedQtyR) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: false,
                id: "requiedInput",
                type: "alert",
                text: globalWorkRegLoc.serialNumberNotEquals,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: globalWorkRegLoc.ok,
                        closeOnAction: true,
                        type: 'primary',
                        action: function () {
                            updateQty = false;
                            if (scrapPcs != sumIssuedQtyP)
                                changeQty($('#scrapPcs'));
                            if (repairPcs != sumIssuedQtyR)
                                changeQty($('#repairPcs'));
                            updateQty = true;
                        }
                    }
                ]
            });
            customModalForMobile(isMobile);
            return false;
        }
    };

    if ($("#wasteSerialNo").val() == "True") {

        if (wastePcs != sumIssuedQtyO) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: false,
                id: "requiedInput",
                type: "alert",
                text: globalWorkRegLoc.serialNumberNotEquals,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: globalWorkRegLoc.ok,
                        closeOnAction: true,
                        type: 'primary',
                        action: function () {
                            updateQty = false;
                            changeQty($('#wastePcs'));
                            updateQty = true;
                        }
                    }
                ]
            });
            customModalForMobile(isMobile);
            return false;
        }
    };

    return true;
};

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) {
                let queryParams = new URLSearchParams(window.location.search);
                queryParams.set('sET','');
                url.search = queryParams.toString();
                new_url = url.toString();
                window.location.href = new_url;
            } 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(globalWorkRegParams.isMobile);

            }

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

}

function deleteWOExRegOperExp(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(),
        QId: $("#QId").val() 
    };

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

            if (response.Success) {
                let queryParams = new URLSearchParams(window.location.search);
                queryParams.set('sET', '');
                url.search = queryParams.toString();
                new_url = url.toString();
                window.location.href = new_url;
            } 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(globalWorkRegParams.isMobile);

            }

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

}

function saveWorkRegOperExp(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(globalWorkRegParams.isMobile);
        return false;
    }

    swapLoadingIcon(true, "saveButton", "fa fa-check");
    $("#saveButton").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($("#Milliseconds").val()),
        GoodPcs: $("#goodPcs").val().replace('.', ','),
        ScrapPcs: $("#scrapPcs").val().replace('.', ','),
        ScrapId: $('#selected-scrap').val(),
        WastePcs: $("#wastePcs").val().replace('.', ','),
        RepairQty: $("#repairPcs").val().replace('.', ','),
        RepairId: $('#selected-repair').val(),
        HoldUps: $("#holdUpQty").val().replace('.', ','),
        HoldUpId: $('#selected-holdup').val(),
        Note: $("#Note").val(),
        Finished: $("#finishOperation").is(":checked") ? "Y" : "N",
        ConfirmReceive: $("#confirmReceive").is(":checked") ? "1" : "0",
        ProdType: globalWorkRegParams.prodType

    };

    $.post(globalWorkRegUrls.saveWOExRegOperExp, data)
    .done(function (response) {
        if (!response.AcKey) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: globalWorkRegLoc.errorSaving,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: globalWorkRegLoc.ok,
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });

            customModalForMobile(globalWorkRegParams.isMobile);
        }
        else {
            location.reload();
        }

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

function InitWoExregOperExp(isSummary = true) {

    var decPlaces = globalWorkRegParams.woExDecPlacesOper;

    globalWorkRegParams.isSummary = isSummary;

    $dataTable = $('#woExRegOperExp');
    $dataTable.DataTable({
        responsive: true,
        serverSide: false,
        scroller: false,
        paging: false,
        destroy: true,
        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";
                d.ParentKey = $("#WoExItem_QId").val();
            }
        },
        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="fal fa-thumbs-up m-r-sm"></i>' + toNumber(full.GoodPcs, decPlaces) + '</span > ' +
                        '<span class="label-primary m-r-sm" style="padding:5px; border-radius:10px">' +
                        '<i class="fal fa-wrench m-r-sm"></i>' + toNumber(full.RepairQty, decPlaces) + '</span>' +
                        '<span class="label-danger m-r-sm" style="padding:5px; border-radius:10px">' +
                        '<i class="fal fa-times m-r-sm"></i>' + toNumber(full.ScrapPcs, decPlaces) + '</span> ' +
                        '<span class="label-primary" style="padding:5px; border-radius:10px">' +
                        '<i class="fal fa-pause m-r-sm"></i>' + toNumber(full.HoldUp, decPlaces) + '</span> ' +
                        ' </div>';
                }
            },
            {
                data: "Note", name: "Note",
                render: function (data, type, full) {
                    var noteClass = data ? "theme-color" : "transparent-color";
                    return type === 'display' ?
                        '<button type="button" class="btn btn-link m-r-sm" data-note="' + data + '" onclick="openWoExOperRegExpNoteModal(this)">' +
                        '<i class="fal fa-comment description-hidden-icon ' + noteClass + '" ></i>' +
                        '</button >' : data;
                }
            }

        ]
    });


}

function initializeMaterialsTab() {
   
    $itemsTable = $('#mainGridMaterials');
    var itemsTable = $itemsTable.DataTable({
        responsive: true,
        serverSide: false,
        scroller: false,
        paging: false,
        destroy: true,
        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);
    $("#Milliseconds").val(seconds * 1000);

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

    element.innerHTML = "<span id='doneTime' style='font-size: 18px' onclick = 'editTime(this)' >" + value + "</span >";

}

function calcTimeFromQty() {

    if ($("#EventType").val() != "")
        return;

    let goodPcs = Number($("#goodPcs").val().replace(",", "."));
    let scrapPcs = Number($("#scrapPcs").val().replace(",", "."));
    let repairPcs = Number($("#repairPcs").val().replace(",", "."));
    let wastePcs = Number($("#wastePcs").val().replace(",", "."));
    let totalPcs = goodPcs + scrapPcs + repairPcs + wastePcs;
    let planQty = Number($("#PlanQty").val().replace(",", "."));

    let planTime = Number($("#PlanTime").val().replace(",", "."));

    let calcTime = planTime * totalPcs / planQty;

    var calcTimeFormat = moment("1900-01-01 00:00:00").add(calcTime, 'hours').format("HH:mm:ss")

    $("#UsedTime").val(calcTime);
    $("#Milliseconds").val(calcTime*3600*1000);
    $("#doneTime").text(calcTimeFormat);

    if (calcTime === 0) {
        $("#start").removeClass("hidden");
        $("#saveButton").addClass("hidden");
    }
    else {
        $("#start").addClass("hidden");
        $("#saveButton").removeClass("hidden");
    }

}

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);
        $('#editOper-ident').val(initialIdent);
        $('#editOper-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;
}

async function getWoExRegOperScraps(anWorkID) {

    await fetch(globalWorkRegUrls.getScrapsURL+ "?workID=" + $("#QId").val(), {
        method: "GET",
        headers: { 'Content-Type': 'application/json' }
    }).then((response) => response.json()
    ).then(async (data) => {
        $('#scrapsTable tbody tr:not(:first)').remove();
        if (data && data.length) {
            for (var i = 0; i < data.length; i++) {
                addScrapsRow(data[i].ScrapId, data[i].Name, data[i].Qty, data[i].RepairQty, data[i].Qid);
            }
        }
    });
}

function addScrapsRow(scrapId, name, qty, repairQty, Qid) {
    var id = Qid ? Qid : 0;

    $('#scrapsTable > tbody:last-child').append(
        '<tr id="tr-scrap-' + id + '" class="sortable-row">' +
        '<td class="serial-numbers-td hidden">' +
        '<input id="scrapId-' + id + '" class="form-control border-bottom-none serialNoCode" value="' + scrapId  + '"  disabled /></td > ' +
        '<td class="serial-numbers-td">' +
        '<input class="form-control border-bottom-none" id="name-' + id + '" value="' + name + '"  disabled /></td>' +
        '<td class="serial-numbers-td">' +
        '<input class="form-control border-bottom-none" id="scrapQty-' + id + '" value="' + qty + '" disabled   /></td>' +
        '<td class="serial-numbers-td">' +
        '<input class="form-control border-bottom-none" id="repairQty-' + id + '" value="' + repairQty + '" disabled   /></td>' +
        '<td class="serial-numbers-td">' +
        '<button type="button" onclick="deleteScrap(\'' + id + '\')" class="btn btn-link editableInput"><span class="far fa-trash-alt"></span></button></td>' +
        '</tr>'
    );

}

async function saveScrap(anQid = null) {

    $("#saveScrapBtn").find("i").addClass("fa-spinner fa-spin");
    $("#saveScrapBtn").prop("disabled", true);

    var data = {

        WorkId: $("#QId").val(), 
        No: $("#AnNo").val(),  
        ScrapId: $("#selected-scrap").val(),  
        Qty: $("#scrapQty").val(), 
        RepairQty: $("#repairQty").val()
    };

    await fetch(globalWorkRegUrls.saveScrapsURL, {
        method: "POST",
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    }).then((response) => response.json()
    ).then(async (response) => {
        $("#saveScrapBtn").find("i").removeClass("fa-spinner fa-spin");
        $("#saveScrapBtn").prop("disabled", false);  

        if (!response || response.Qid === 0 || (response.Qty + response.RepairQty == 0)) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: response.Qid === 0 ? globalWorkRegLoc.scrapReason : globalWorkRegLoc.requiedQty,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#ConfirmLoc").val(),
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        } else {
            addScrapsRow(response.ScrapId, response.Name, response.Qty, response.RepairQty, response.Qid);
            $("#scrapPcs").val(Number(response.PaWoExRegOperExp.ScrapPcs));
            $("#repairPcs").val(Number(response.PaWoExRegOperExp.RepairQty));           
            $("#selected-scrap").val("");
            $("#scrapQty").val(0);
            $("#repairQty").val(0);
            $('#selected-scrap').trigger("change");
            $("#selected-scrap").focus();
        }
    });
}

async function deleteScrap(anQid) {

    var data = {
        WorkId: $("#QId").val(),
        Qid: anQid,
        Qty: $("#scrapQty-" + anQid).val(),
        RepairQty: $("#repairQty-" + anQid).val()

    };

    await fetch(globalWorkRegUrls.deleteScrapsURL, {
        method: "POST",
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    }).then((response) => response.json()
    ).then(async (response) => {
        if (response && response.Success === true) {
            $("#scrapPcs").val(Number($("#scrapPcs").val()) - Number($("#scrapQty-" + anQid).val()));
            $("#repairPcs").val(Number($("#repairPcs").val()) - Number($("#repairQty-" + anQid).val()));
            $("#tr-scrap-" + anQid).remove();
        }
    });
}

async function getWoExRegOperHoldUps(anWorkID) {
    await fetch(globalWorkRegUrls.getHoldUpsURL + "?workID=" + $("#QId").val(), {
        method: "GET",
        headers: { 'Content-Type': 'application/json' }
    }).then((response) => response.json()
    ).then(async (data) => {
        $('#holdupsTable tbody tr:not(:first)').remove();
        if (data && data.length) {
            for (var i = 0; i < data.length; i++) {
                addHoldUpsRow(data[i].HoldId, data[i].Name, data[i].Time, data[i].Qid);
            }
        }
    });
}

function addHoldUpsRow(holdUpId, name, qty, Qid) {
    var id = Qid ? Qid : 0;

    $('#holdupsTable > tbody:last-child').append(
        '<tr id="tr-holdup-' + id + '" class="sortable-row">' +
        '<td class="serial-numbers-td hidden">' +
        '<input id="holdUpId-' + id + '" class="form-control border-bottom-none serialNoCode" value="' + holdUpId + '"  disabled /></td > ' +
        '<td class="serial-numbers-td">' +
        '<input class="form-control border-bottom-none" id="name-' + id + '" value="' + name + '"  disabled /></td>' +
        '<td class="serial-numbers-td">' +
        '<input class="form-control border-bottom-none" id="holdUpQty-' + id + '" value="' + qty + '" disabled /></td>' +
        '<td class="serial-numbers-td">' +
        '<button type="button" onclick="deleteHoldUp(\'' + id + '\')" class="btn btn-link editableInput"><span class="far fa-trash-alt"></span></button></td>' +
        '</tr>'
    );

}

async function saveHoldUp(anQid = null) {

    $("#saveHoldUpBtn").find("i").addClass("fa-spinner fa-spin");
    $("#saveHoldUpBtn").prop("disabled", true);

    var data = {

        WorkId: $("#QId").val(),
        No: $("#AnNo").val(),
        HoldUpId: $("#selected-holdup").val(),
        Time: $("#holdUpQty-1").val()
    };

    await fetch(globalWorkRegUrls.saveHoldUpsURL, {
        method: "POST",
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    }).then((response) => response.json()
    ).then(async (response) => {
        $("#saveHoldUpBtn").find("i").removeClass("fa-spinner fa-spin");
        $("#saveHoldUpBtn").prop("disabled", false);

        if (!response || response.Qid === 0 || response.Time == 0) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: response.Qid === 0 ? globalWorkRegLoc.holdUpReason : globalWorkRegLoc.requiedQty,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#ConfirmLoc").val(),
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        } else {
            addHoldUpsRow(response.HoldUpId, response.Name, response.Time, response.Qid);            
            $("#holdUpQty").val(Number(response.PaWoExRegOperExp.HoldUp));
            $("#selected-holdup").val("");
            $("#holdUpQty-1").val(0);
            $('#selected-holdup').trigger("change");
            $("#selected-holdup").focus();
        }
    });
}

async function deleteHoldUp(anQid) {

    var data = {
        WorkId: $("#QId").val(),
        Qid: anQid,
        Time: $("#holdUpQty-" + anQid).val()
    };

    await fetch(globalWorkRegUrls.deleteHoldUpsURL, {
        method: "POST",
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    }).then((response) => response.json()
    ).then(async (response) => {
        if (response && response.Success === true) {
            $("#holdUpQty").val(Number($("#holdUpQty").val()) - Number($("#holdUpQty-" + anQid).val()));
            $("#tr-holdup-" + anQid).remove();
        }
    });
}
