var globalReceivingLoc;
var globalReceivingUrls;
var globalReceivingParams;
var woExDecPlacesProd;

function initializeWorkOrderReceiving(localizations, urls, params) {

    globalReceivingLoc = localizations;
    globalReceivingUrls = urls;
    globalReceivingParams = params;
    woExDecPlacesProd = globalReceivingParams.woExDecPlacesProd; 

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

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

    $('input[type=number]').on('keydown', function (e) {

        var pattern = "^\\d*(\\.\\d{0," + woExDecPlacesProd +"})?$";
        var input = $(this);
        var oldVal = input.val();
        var regex = new RegExp(pattern, 'g');

        setTimeout(function () {
            var newVal = input.val();
            if (!regex.test(newVal)) {
                input.val(oldVal);
            }
        }, 1);
    });


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

    $('#goodPcs').on("change", function () {
        if (Number($("#RestQty").val().replace(',', '.')) <= Number($("#goodPcs").val())) {
            if (!$("#finish-task").hasClass('active')) {
                $("#finish-task").addClass("active");
                $("#finish-task :input").prop('checked', true);
            }
        } else {
            if ($("#finish-task").hasClass('active')) {
                $("#finish-task").removeClass("active");
                $("#finish-task :input").prop('checked', false);
            }
        }
    });

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

        openSideContent();
    });

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

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

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

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

    });

    $('#apply, #back').on("click", function () {
        closeSideContent()
    });

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

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

    if ($("#Picture").val() == "") {

        $("#image").addClass('hidden');
        $("#noImage").removeClass('hidden');

    }

    if ($("#productionTypeMF").val() === $("#ProdType").val()) {
        setGlobalExampleHelpUrl($("#manufacturingExampleMF").val());
    } else if ($("#productionTypeSE").val() === $("#ProdType").val()) {
        setGlobalExampleHelpUrl($("#manufacturingExampleSE").val());
    }


    $(".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')) {
            e.preventDefault();
            $('#' + controlId).trigger('click');
        }
    });

    getSerialNumbersForIdentR();

    $('#identSerialNoModal').on('shown.bs.modal', function () {
        getSerialNumbersForIdentR();
    });
    
};

function confirmReceive(isMobile) {

    if (!validationData(isMobile)) return;

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

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

        if (this.name == "Finished") {
            this.value = 'true'
        }
    });

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

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

            if (response.Success) {

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: false,
                    id: "displayPopupSuccessModal",
                    type: "success",
                    text: globalReceivingLoc.succes,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: globalReceivingLoc.ok,
                            closeOnAction: true,
                            type: 'primary',
                            action: function () {
                                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: globalReceivingLoc.ok,
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
                customModalForMobile(isMobile);
            }

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

}

function validationData(isMobile) {
   
    var goodPcs = Number($("#goodPcs").val());
    var scrapPcs = Number($("#scrapPcs").val());
    var repairPcs = Number($("#repairPcs").val());
    var wastePcs = Number($("#wastePcs").val());

    if (goodPcs + scrapPcs + repairPcs + wastePcs == 0) {

        $().customModal({
            destroyOnClose: true,
            showCloseButton: false,
            id: "requiedInput",
            type: "alert",
            text: globalReceivingLoc.requiedQty,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: globalReceivingLoc.ok,
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
        customModalForMobile(isMobile);
        return false;
    };

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

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

    return true;
};

function getReceivingWarehouse() {
    return $('.warehouse-list-item.active').data('value');
};

function addRest(context, qty) {

    var name = context.id.substring(1);
    var value = parseInt(qty);

    $("#" + name).val(roundToPercision(woExDecPlacesProd, value));
    $("#" + name).trigger('blur');
}

//SERIAL NUMBERS FOR RECEIVINGS

var sumIssuedQtyK = 0;
var sumIssuedQtyO = 0;
var sumIssuedQtyP = 0;
var sumIssuedQtyR = 0;
let updateQty = true;

function changeQty(obj) {

    if ((obj.attr("data-serialNo-type") == "K" && $("#serialNo").val() == "False") ||
        (obj.attr("data-serialNo-type") == "P" && $("#scrapSerialNo").val() == "False") ||
        (obj.attr("data-serialNo-type") == "R" && $("#scrapSerialNo").val() == "False") ||
        (obj.attr("data-serialNo-type") == "O" && $("#wasteSerialNo").val() == "False"))
        return;

    $("#identSerialNoQuantity").attr('step', woExDecPlacesProd)
    $("#input-serial-quantity").attr('step', woExDecPlacesProd)

    $("#serialNoType-0").val(obj.attr("data-serialNo-type"));
    $("#quantity-0").val(obj.val());
    $("#SerialNoWOType").val(globalReceivingParams ? globalReceivingParams.serialNoWOType : globalWorkRegParams.serialNoWOType);

    if ($("#serialNoType-0").val() == "P" && $("#ScrapIdent").val() != "" && $("#scrapSerialNo").val() != "N" )
        $("#id-0").val($("#ScrapIdent").val());
    if ($("#serialNoType-0").val() == "R" && $("#ScrapIdent").val() != "" && $("#scrapSerialNo").val() != "N")
        $("#id-0").val($("#ScrapIdent").val());
    if ($("#serialNoType-0").val() == "O" && $("#WasteIdent").val() != "" && $("#wasteSerialNo").val() != "N")
        $("#id-0").val($("#WasteIdent").val());

    checkIdentSerialNo(0, "P", obj.attr("data-serialNo-type"), 1);

    if ($("#serialNo-0").val() == "K")
        $("#input-serial-quantity").val(null);

    formatNumberInput($("#identSerialNoQuantity"));
}

function changeIdentData(anNo) {
    getSerialNumbersForIdentR();
}

function save(option, printType, deleteBPBI = false) {
    //Override function
}

async function getSerialNumbersForIdentR() {

    if ($("#serialNo-0").val() == "N")
        return;

    sumIssuedQtyK = 0;
    sumIssuedQtyO = 0;
    sumIssuedQtyP = 0;
    sumIssuedQtyR = 0;

    await fetch("GetSerialNumbers?key=" + $("#AcKey").val() + '&type=X' , {
        method: "GET",
        headers: { 'Content-Type': 'application/json' }
    }).then((response) => response.json()       
    ).then(async (data) => {

        $('#identSerialNoGrid tbody tr:not(:first)').remove();
        if (data && data.length) {
            for (var i = 0; i < data.length; i++) {

                if (data[i].Type == $("#serialNoType-0").val()) 
                    addSerialNumberRow(data[i].SerialNo, data[i].Qty, data[i].DateDue, data[i].Qid);

                $("#serialNoQty-" + data[i].Qid).attr('step', woExDecPlacesProd);
                formatNumberInput($("#serialNoQty-" + data[i].Qid));

                if (data[i].Type == "K")
                    sumIssuedQtyK += data[i].Qty;
                if (data[i].Type == "O")
                    sumIssuedQtyO += data[i].Qty;
                if (data[i].Type == "P")
                    sumIssuedQtyP += data[i].Qty;
                if (data[i].Type == "R")
                    sumIssuedQtyR += data[i].Qty;

            }
        }
    });

    if (updateQty) {

        switch ($("#serialNoType-0").val()) {

            case "K":
                $("#goodPcs").val(sumIssuedQtyK); break;
            case "O":
                $("#wastePcs").val(sumIssuedQtyO); break;
            case "P":
                $("#scrapPcs").val(sumIssuedQtyP); break;
            case "R":
                $("#repairPcs").val(sumIssuedQtyR); break;
            case "X":
                $("#goodPcs").val(sumIssuedQtyK);
                $("#wastePcs").val(sumIssuedQtyO);
                $("#scrapPcs").val(sumIssuedQtyP);
                $("#repairPcs").val(sumIssuedQtyR);
                break;
        }
    }

    $("#input-serial-no").off('keydown');
    $("#input-serial-no").on('keydown', function (e) {
        if ($("#input-serial-no").val() && $("#input-serial-no").val() !== "" && (e.keyCode === 13 || e.key === 'Enter')) {
            e.preventDefault();
            $("#input-serial-quantity").focus();
        }
    });

    $("#input-serial-quantity").off('keydown');
    $("#input-serial-quantity").on('keydown', function (e) {
        if ($("#input-serial-quantity").val() && $("#input-serial-quantity").val() !== "" && (e.keyCode === 13 || e.key === 'Enter')) {
            e.preventDefault();
            saveSerialNo();
            $("#input-serial-no").focus();
        }
    });
}

async function saveSerialNo(anQid = null) {    

    var id = anQid;
    var serialNo = $("#identSerialNo-" + anQid).val();
    var $serialCodes = $(".serialNoCode");
    if ($serialCodes && $serialCodes.length) {
        for (var i = 0; i < $serialCodes.length; i++) {
            if ($serialCodes[i].value === $("#input-serial-no").val()) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: globalReceivingLoc.serialNumberValueAlreadyExist,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: globalReceivingLoc.confim,
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });

                return;
            }
        }
    }

    if (anQid == null && Number($("#input-serial-quantity").val()) == 0) {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "error",
            text: globalReceivingLoc.requiedSerialQty,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: globalReceivingLoc.confim,
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });

        return;

    }

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

    var serialNoQtySum = getSerialNoQtySum($("#serialNoType-0").val());

    if (!serialNo)
        serialNoQtySum = serialNoQtySum + toNumber($("#input-serial-quantity").val().replace('.', ''));

    serialNo = serialNo ? serialNo : $("#input-serial-no").val();
    serialNoDateDue = $("#serialNoDateDue-" + id).val() ? $("#serialNoDateDue-" + id).datepicker("getDate") : $("#input-serial-dateDue").datepicker("getDate");

    var data = {
        AcKey: $("#AcKey").val(),
        AnNo: $("#IdentAnNo").val(),
        Ident: $("#identSerialNoIdent").val(),
        SerialNo: serialNo,
        Qty: $("#serialNoQty-" + id).val() ? $("#serialNoQty-" + id).val().replace('.', ',') : $("#input-serial-quantity").val().replace('.', ','),
        DateDue: "1900-01-01",
        Type: $("#serialNoType-0").val(),
        SNWOType: $("#SerialNoWOType").val(), 
        Package: "",
        PackQty: 0
    };

    var currDate = (new Date()).toISOString().split('T')[0];
    if ($("#IdentSerialDateDue").val() === "true" && new Date(moment(serialNoDateDue).format('YYYY-MM-DD')) < new Date(currDate)) {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "success",
            text: globalReceivingLoc.dateDueExpiredForSerialNumber + serialNo,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: globalReceivingLoc.confim,
                    action: async function () {
                        checkSerialNumberQtySum(serialNoQtySum);
                    },
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    } else
        checkSerialNumberQtySum(serialNoQtySum);

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

        if (!response || response === false) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: globalReceivingLoc.errorSaving,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: globalReceivingLoc.confim,
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        } else {
            if ($("#input-serial-no").val()) {
                addSerialNumberRow($("#input-serial-no").val(), $("#input-serial-quantity").val(), $("#input-serial-dateDue").val());
                $("#input-serial-no").val("");
                $("#input-serial-dateDue").datepicker("setDate", $("#IdentSerialInvoiceDate").val());
                if ($("#serialNo-0").val() == "K")
                    $("#input-serial-quantity").val(null);
            } else {
                $("#savedSerialNoQty-" + id).val(data.QuantityNew);
                $("#savedSerialNoDateDue-" + id).val(new Date($("#serialNoDateDue-" + id).datepicker("getDate")).toISOString());
            }

        }
    });
}

async function deleteSerialNo(id) {

    var serialNoQtySum = getSerialNoQtySum($("#IdentSerialNoType").val());
    serialNoDateDue = $("#serialNoDateDue-" + id).val() ? $("#serialNoDateDue-" + id).datepicker("getDate") : $("#input-serial-dateDue").datepicker("getDate");

    var data = {
        AcKey: $("#AcKey").val(),
        AnNo: $("#IdentAnNo").val(),
        Issuer: $("#ReceiverId").val(),
        Ident: $("#identSerialNoIdent").val(),
        SerialNo: $("#identSerialNo-" + id).val(),
        Quantity: serialNoQtySum,
        QuantityOld: 0,
        QuantityNew: $("#serialNoQty-" + id).val(),
        DateDueNew: $("#IdentSerialDateDue").val() === "true" ? serialNoDateDue : null,
        DateDue: $("#IdentSerialDateDue").val() === "true" ? serialNoDateDue : null,
        Type: $("#IdentSerialNoType").val(),
        SNWOType: "PP",
        Package: "",
        PackQty: 0,
        Qid: id,
        InvoiceType: $("#InvoiceType").val(),
        SNType: $("#IdentSerialNoType").val()
    };

    await fetch("DeleteByAcKeyAndSerialNo", {
        method: "POST",
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    }).then((response) => response.json()
    ).then(async (response) => {
        if (response && response === true) {
            $("#tr-serial-" + id).remove();
        }
    });
}

async function deleteAll(deleteAllTypes = false) {

    var data = {
        AcKey: $("#AcKey").val(),
        AnNo: $("#IdentAnNo").val(),
        Ident: $("#identSerialNoIdent").val(),
        Type: !deleteAllTypes ? $("#serialNoType-0").val() : "X",
        SNWOType: $("#SerialNoWOType").val(),
        SNType: $("#IdentSerialNoType").val()
    };

    var url = $("#SerialNoWOType").val() === "PP" ? "DeleteAllSerialNoByAcKey" : "DeleteAllIssuedByAcKey";
    await fetch(url, {
        method: "POST",
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    }).then((response) => response.json()
    ).then((data) => {
        if (data && data === true) {
            $('#identSerialNoGrid tbody tr:not(:first)').remove();
        }
    });
}

async function multiplySerialNumbers() {

    if ($("#identSerialNoQty").val() > 0) {
        $("#multiplySerialsBtn").find("i").addClass("fa-spinner fa-spin");
        $("#multiplySerialsBtn").prop("disabled", true);

        var serialNoQtySum = getSerialNoQtySum($("#serialNoType-0").val());
        var serial = $("#identSerialNoSerial").val();
        var serialLength = serial.length;

        for (var i = 0; i < $("#identSerialNoQty").val(); i++) {
            var data = {
                AcKey: $("#AcKey").val(),
                AnNo: $("#IdentAnNo").val(),
                Receiver: $("#receivingWarehouse").val(),
                Ident: $("#identSerialNoIdent").val(),
                SerialNo: $("#identSerialNoPrefix").val() + serial,
                Quantity: serialNoQtySum,
                QuantityOld: 0,
                QuantityNew: $("#IdentSerialNoType").val() === "S" || $("#IdentSerialNoType").val() === "E" ? 1 : 0,
                Type: $("#serialNoType-0").val(),
                SNWOType: "PP",
                Package: "",
                PackQty: 0,
                InvoiceType: $("#InvoiceType").val(),
                DateDue: $("#IdentSerialDateDue").val() === "true" ? $("#IdentSerialInvoiceDate").val() : null,
                SNType: $("#IdentSerialNoType").val()
            };        

            await fetch('/SerialNumbers/SerialNoUpd', {
                method: "POST",
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            }).then((response) => response.json()
            ).then(async (response) => {
                if (!response || response === false) {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "alert",
                        text: "@Loc.ErrorSaving",
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: globalReceivingLoc.confim,
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                } else {
                    addSerialNumberRow($("#identSerialNoPrefix").val() + serial, data.QuantityNew, data.DateDue);
                }
            });

            serial = pad(toNumber(serial) + 1, serialLength);
        }

        $("#multiplySerialsBtn").find("i").removeClass("fa-spinner fa-spin");
        $("#multiplySerialsBtn").prop("disabled", false);
    }
}

function getSerialNoQtySum(type = null) {
    if (type == "K") return sumIssuedQtyK
    else
        if (type == "O") return sumIssuedQtyO
        else
            if (type == "P") return sumIssuedQtyP
            else
                return sumIssuedQtyK + sumIssuedQtyO + sumIssuedQtyP;

}



