var globalEditMatParams;
var globalEditMatLoc;
var globalEditMatUrls;

function initializeServicesEditMat(localizations, urls, params) {
    globalEditMatParams = params;
    globalEditMatLoc = localizations;
    globalEditMatUrls = urls;

    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(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('change');
        control.trigger('blur');
    });

    $('#image').on("click", function () {
        $("#imageModal").modal('show');
    });

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

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

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

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

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

        $('#billableWarehouse').val($(this).data("value"));
        $('#mbWarehouse').text($(this).data("value"));

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

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

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

        $('#ncWarehouse').val($(this).data("value"));
        $('#mncWarehouse').text($(this).data("value"));

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

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

    $('#billableWarehouse').on("change", function () {
        loadIdentStockForWarehouse($('#Ident').val(), $('#billableWarehouse').val(), '#billable-stock');
    });

    $('#ncWarehouse').on("change", function () {
        loadIdentStockForWarehouse($('#Ident').val(), $('#ncWarehouse').val(), '#nc-stock');
    });

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

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

        $('#confirmButton').attr('onclick', 'UpdatePosition(this)');
    });

    if ('@_isMobile' === 'True') {
        $('#ident').on('click', function () {
            $('#tabCaption').text(globalEditMatParams.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("value"));
            $('#Ident').val($(this).data("value"));

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

            $('#mConfirmButton').attr('onclick', 'UpdatePosition(this)');
        });
    }

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

}
function changeQty(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") {
                $("#billableQty").val(qtyK);
                $("#nonChargeableQty").val(qtyP);
            }

        }

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

function loadIdentStockForWarehouse(ident, warehouse, stockId) {
    $.ajax({
        type: 'GET',
        url: globalEditMatUrls.getIdentStockOnWarehouse,
        data: {
            ident: ident,
            warehouse: warehouse
        },
        success: function (response) {
            $(stockId).text(response.Stock);
        },
        error: function (error) {
            console.error(error);
        }
    });
}

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: globalEditMatParams.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 incrementQuantity(anSubNo, anResursQId, isSml = false) {

    if ($('#StatusMF').val() == 'Z')
        return;

    let input;
    if (isSml) {
        input = document.getElementById(anSubNo + '-' + anResursQId + '-quantity-sml');
    } else {
        input = document.getElementById(anSubNo + '-' + anResursQId + '-quantity');
    }

    input.value = parseInt(input.value) + 1;

    updateQuantity(anSubNo, anResursQId, input.value, isSml);
}

function decrementQuantity(anSubNo, anResursQId, isSml = false) {
    if ($('#StatusMF').val() == 'Z')
        return;

    let input;
    if (isSml) {
        input = document.getElementById(anSubNo + '-' + anResursQId + '-quantity-sml');
    } else {
        input = document.getElementById(anSubNo + '-' + anResursQId + '-quantity');
    }

    if (parseInt(input.value) > 0) {
        input.value = parseInt(input.value) - 1;
        updateQuantity(anSubNo, anResursQId, input.value, isSml);
    }
}

function updateQuantity(anSubNo, anResursQId, value, isSml = false) {
    $.ajax({
        cache: false,
        type: "POST",
        url: $('#UpdateToolQuantityURL').val(),
        data: {
            anSubNo: anSubNo,
            anResursQId: anResursQId,
            quantity: value,
            isSml: isSml
        },
        error: function (error) {
            console.error(error)
        }
    });
}

function confirmIssueMaterial(button) {

    let buttonId = $(button).attr('id');
    const billableQty = toNumber($("#billableQty").val());
    const nonChargeableQty = toNumber($("#nonChargeableQty").val());

    if (billableQty + nonChargeableQty == 0){
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            id: "requiedInput",
            type: "alert",
            text: globalEditMatLoc.requiredText,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: globalEditMatLoc.ok,
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
        customModalForMobile();
        return false;
    };

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

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

    if (!formData.some(item => item.name === "BillableWarehouse")) {
        formData.push({ name: "BillableWarehouse", value: $("#mbWarehouse").text() });
    }

    if (!formData.some(item => item.name === "NonChargeableWarehouse")) {
        formData.push({ name: "NonChargeableWarehouse", value: $("#mncWarehouse").text() });
    }

    swapLoadingIcon(true, buttonId, "fa fa-check");

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

            if (response.Success) {

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

            } else {

                let errorText = response.Error;

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

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