var globalEditMatParams;
var globalEditMatLoc;
var globalEditMatUrls;

function initializeWorkOrderEditMat(localizations, urls, params) {
    globalEditMatParams = params;
    globalEditMatLoc = localizations;
    globalEditMatUrls = urls;
    globalEditMatParams.isMobile = globalEditMatParams.isMobile == 'True' ? true : false;

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

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

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

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

    $('#issueWarehouse').on("change", function () {
        loadIdentStockForWarehouse($('#Ident').val(), $('#issueWarehouse').val());
    });

    $('#editMat-ident').on('change', function () {
        const ident = $('#editMat-ident').val();
        $('#Ident').val(ident);

        $('#confirmButton').attr('onclick', 'UpdatePosition(this)');
    });
    if (globalEditMatParams.isMobile) {
        $('#ident').on('click', function () {
            $('#tabCaption').text(globalEditMatLoc.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 () {
            $('.ident-list-item').find('i').removeClass('fa-check');
            $('.ident-list-item').removeClass('active');

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

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

            $('#mConfirmButton').attr('onclick', 'UpdatePosition(this)');
            $('.btn-close-side-panel').click();
        });
    }


    $('.warehouse-list-item').on("click", function () {
        $('.warehouse-list-item').find('i').removeClass('fa-check');
        $('.warehouse-list-item').removeClass('active');

        $('#issueWarehouse').val($(this).data("value"));
        $('#mWarehouse').text($(this).data("value"));

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

        loadIdentStockForWarehouse($('#Ident').val(), $(this).data("value"));
    });

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

    });

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

    var decPlaces = $("#WoExDecPlacesMate").val();

    $('.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(Number(control.val()) + 1);
        };

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

        control.trigger('change');
        control.trigger('blur');

    });

    initializeIssuedSerialNumbers({
        serialNumberQuantityIsReached: globalEditMatLoc.serialNumberQuantityIsReached,
        numberOfSerialNumbersIsGreaterThanOnDocument: globalEditMatLoc.numberOfSerialNumbersIsGreaterThanOnDocument,
        serialNumberValueAlreadyExist: globalEditMatLoc.serialNumberValueAlreadyExist,
        automaticIssueOfSerialNumbersNotPossible: globalEditMatLoc.automaticIssueOfSerialNumbersNotPossible,
        selectedSerialNumberDoesNotExistInWarehouse: globalEditMatLoc.selectedSerialNumberDoesNotExistInWarehouse,
        dateDueExpiredForSerialNumber: globalEditMatLoc.dateDueExpiredForSerialNumber,
        desiredQuantity: globalEditMatLoc.desiredQuantity,
        actualQuantity: globalEditMatLoc.actualQuantity,
        difference: globalEditMatLoc.difference,
        errorSaving: globalEditMatLoc.errorSaving,
        confirm: globalEditMatLoc.confirm,
        cancel: globalEditMatLoc.cancel
    },
        {
            moveUpdateSerialNoUrl: globalEditMatUrls.moveUpdateSerialNoUrl,
            serialNoUpdUrl: globalEditMatUrls.globalEditMatUrls,
            deleteByAcKeyAndSerialNoUrl: globalEditMatUrls.deleteByAcKeyAndSerialNoUrl,
            deleteIssuedByAcKeyAndSerialNo: globalEditMatUrls.deleteIssuedByAcKeyAndSerialNo,
            deleteAllIssuedByAcKey: globalEditMatUrls.deleteAllIssuedByAcKey,
            deleteUnusedItemSerialsUrl: globalEditMatUrls.deleteUnusedItemSerialsUrl,
            createSerialNoUrl: globalEditMatUrls.createSerialNoUrl,
            moveSerialNoAddSalesUrl: globalEditMatUrls.moveSerialNoAddSalesUrl,
            getByAcKeyAndAnNoUrl: globalEditMatUrls.getByAcKeyAndAnNoUrl,
            serialNoAutoEditionUrl: globalEditMatUrls.serialNoAutoEditionUrl,
            getFreeSerialNumbers: globalEditMatUrls.getFreeSerialNumbers,
            refreshStockSerialNoOnDay: globalEditMatUrls.refreshStockSerialNoOnDay,
            checkQuantitySetting: globalEditMatUrls.checkQuantitySetting
        }, globalEditMatParams.issueWarehouse, false);

    getSerialNumbersIssueForIdent(globalEditMatParams.anNo);

    $('#identSerialNoIssueModal').on('hidden.bs.modal', function (e) {
        var qty = getSerialNoQtySumIssue();

        if ($("#IdentSerialNoTypeIssue").val() == "K")
            $("#qty").val(qty);
        if ($("#IdentSerialNoTypeIssue").val() == "O")
            $("#wasteQty").val(qty);
        if ($("#IdentSerialNoTypeIssue").val() == "P")
            $("#scrapQty").val(qty);
    })

    $("#qty").on('keydown', function (e) {
        var qty = $("#qty").val() 
        if ((qty > 0) && (e.keyCode === 13 || e.key === 'Enter')) {
            e.preventDefault();
            changeQtyMat(this.id, 'K')
        }
    });
    $("#scrapQty").on('keydown', function (e) {
        var qty = $("#scrapQty").val()
        if ((qty > 0) && (e.keyCode === 13 || e.key === 'Enter')) {
            e.preventDefault();
            changeQtyMat(this.id, 'P')
        }
    });
    $("#wasteQty").on('keydown', function (e) {
        var qty = $("#wasteQty").val()
        if ((qty > 0) && (e.keyCode === 13 || e.key === 'Enter')) {
            e.preventDefault();
            changeQtyMat(this.id, 'O')
        }
    });

}

function saveMaterial(button) {

    var buttonId = $(button).attr('id');

    var receiveURL = $("#receiveURL").val();
    var buttonText = $("#buttonText").val();
    var succesText = $("#succesText").val();

    var formData = $("#workOrderEditMat").serializeArray();

    $.each(formData, function () {
        if (!isNaN(this.value)) {
            this.value = this.value.replace('.', ',');
        }
    });

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

    $.post(receiveURL, formData)
        .done(function (response) {

            if (response.Success) {

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    id: "displayPopupSuccessModal",
                    type: "success",
                    text: succesText,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: buttonText,
                            closeOnAction: true,
                            type: 'primary',
                            action: function () {
                                location.reload();
                            }
                        }
                    ]
                });
                customModalForMobile(globalEditMatParams.isMobile);

            } else {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    id: "displayPopupErrorModal",
                    type: "alert",
                    text: response.Error,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: buttonText,
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
                customModalForMobile(globalEditMatParams.isMobile);

            }

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

}

function changeQtyMat(obj, type) {

    if ($("#SerialNo").val() == "N")
        return;

    $("#serialNoType-" + globalEditMatParams.anNo).val(type);
    $("#quantity-" + globalEditMatParams.anNo).val($('#' + obj).val());

    $("#SerialNoWOTypeIssue").val(globalEditMatParams.serialNoWOType);
    $("#SerialNoMoveTypeIssue").val(type);

    checkIdentSerialNoIssue(globalEditMatParams.anNo, "M", type, 1, 'false');

}

async function getSerialNumbersIssueForIdent(anNo) {

    await fetch(globalIssuedSerialNumbersUrls.getByAcKeyAndAnNoUrl + "?key=" + $("#AcKey").val() + "&no=" + anNo + "&type=" + $("#serialNoType-" + anNo).val(), {
        method: "GET",
        headers: { 'Content-Type': 'application/json' }
    }).then((response) => response.json()
    ).then(async (data) => {
        $('#identSerialNoGridIssue tbody tr').remove();
        var qty = 0;
        var qtyK = 0;
        var qtyO = 0;
        var qtyP = 0;

        if (data && data.length) {
            for (var i = 0; i < data.length; i++) {
                addSerialNumberIssueRow(data[i].SerialNo, data[i].Qty, null, data[i].DateDue, data[i].AnQid);
                qty = qty + data[i].Qty;

                if (data[i].Type == "K")
                    qtyK = qtyK + data[i].Qty;
                if (data[i].Type == "O")
                    qtyO = qtyO + data[i].Qty;
                if (data[i].Type == "P")
                    qtyP = qtyP + data[i].Qty;
            }

            if ($("#serialNoType-" + anNo).val() == "X") {
                $("#qty").val(qtyK);
                $("#wasteQty").val(qtyO);
                $("#scrapQty").val(qtyP);
            }

        }

        $("#identSerialNoQuantityIssue").val(qty);
        $("#identSerialNoDifferenceIssue").val(Math.abs(toNumber($("#identSerialNoReqQuantityIssue").val())) - toNumber($("#identSerialNoQuantityIssue").val()));
        formatNumberInput($("#identSerialNoQuantityIssue"));
        formatNumberInput($("#identSerialNoDifferenceIssue"));
    });
}

function UpdatePosition(button) {
    var buttonId = $(button).attr('id');
    var formData = $("#workOrderEditMat").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: globalEditMatUrls.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: globalEditMatLoc.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 loadIdentStockForWarehouse(ident, warehouse) {
    $.ajax({
        type: 'GET',
        url: globalEditMatUrls.getIdentStockOnWarehouse,
        data: {
            ident: ident,
            warehouse: warehouse
        },
        success: function (response) {
            $('#stock').text(response.Stock);
        },
        error: function (error) {
            console.error(error);
        }
    });
}
