var woExDecPlacesProd = $("#WoExDecPlacesProd").val();

function initializeWorkOrderReceiving() {
    $(".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));

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

    $('#finished').on("change", function () {
        if (Number($("#RestQty").val().replace(',', '.')) <= Number($("#finished").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);
            }
        }
    });

    $('#options').on("click", function () {
        $('#sideNavBar>.tab-pane').removeClass("active");
        $('#tabNav>.divided-tab-2').removeClass("active");
        $('#tabNav>#homeTab').addClass("active");
        $('#sideNavBar>#additional-settings').addClass("fade").addClass("in").addClass("active");
        $(".divided-content").addClass("divided-content-side-opened").removeClass("divided-content-side-closed");

        var caption = $("#additional-settings").data('tab-caption');
        $("#tabCaption").text(caption);
    });

    $('#warehouse').on("click", function () {
        $('#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");

        var caption = $("#warehouse-list").data('tab-caption');
        $("#tabCaption").text(caption);
    });

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

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

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

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

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

    getSerialNumbersForIdent();
};

function saveReceive(isMobile) {
    var qty = $("#finished").val();

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

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

    $.post($("#receiveURL").val(), formData)
        .done(function (response) {
            if (response.Success) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: false,
                    id: "displayPopupSuccessModal",
                    type: "success",
                    text: $("#succesText").val(),
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: $("#buttonText").val(),
                            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: $("#buttonText").val(),
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
                customModalForMobile(isMobile);
            }
            swapLoadingIcon(false, "confirmButton", "fa fa-check");
        });
}

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

function customModalForMobile(isMobile) {
    if (isMobile) {
        $(".custom-modal-footer>div>button").addClass("btn-rounded");
        $(".custom-modal-body-content>span").addClass("h4");
        $(".custom-modal-title").css("font-size", 24);
    }
}

//SERIAL NUMBERS FOR RECEIVINGS
function changeQty(obj, type) {
    $("#serialNoType-0").val(type);
    $("#quantity-0").val($('#'+obj).val()).change();

    checkIdentSerialNo(0, "P", null, 1, 'false');
}

function changeIdentData(anNo) {
    //Override function
    var sumQty = getSerialNoQtySum();

    if ($("#serialNoType-0").val() == "K")
        $("#finished").val(sumQty);
    if ($("#serialNoType-0").val() == "O")
        $("#waste").val(sumQty);
    if ($("#serialNoType-0").val() == "P")
        $("#scrap").val(sumQty);
}

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

async function getSerialNumbersForIdent(anNo) {
    await fetch("GetSerialNumbers?key=" + $("#AcKey").val() + '&type=' + $("#serialNoType-0").val(), {
        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++) {
                addSerialNumberRow(data[i].SerialNo, data[i].Qty, data[i].DateDue);
            }
            getSerialNoQtySum(data);
        }
    });
}

async function saveSerialNo(serialNo = null) {
    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: $("#serialNumberValueAlreadyExist").val(),
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: $("#ConfirmLoc").val(),
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });

                return;
            }
        }
    }

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

    var serialNoQtySum = getSerialNoQtySum();
    if (!serialNo)
        serialNoQtySum = serialNoQtySum + toNumber($("#input-serial-quantity").val());

    serialNo = serialNo ? serialNo : $("#input-serial-no").val();
    var id = serialNo.replace(/ /g, '');
    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() : $("#input-serial-quantity").val(),
        DateDue: "1900-01-01",
        Type: $("#serialNoType-0").val(),
        SNWOType: "PP",
        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: $("#dateDueExpiredForSerialNumber").val() + serialNo,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: $("#ConfirmLoc").val(),
                    action: async function () {
                        checkSerialNumberQtySum(serialNoQtySum);
                    },
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    } else
        checkSerialNumberQtySum(serialNoQtySum);

    await fetch("AddSerialNo", {
        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: $("#errorSaving").val(),
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#ConfirmLoc").val(),
                        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());
                $("#input-serial-quantity").val(1);
            } else {
                $("#savedSerialNoQty-" + id).val(data.QuantityNew);
                $("#savedSerialNoDateDue-" + id).val(new Date($("#serialNoDateDue-" + id).datepicker("getDate")).toISOString());
            }

            $("#identSerialNoQuantity").val(serialNoQtySum);
        }
    });
}

async function deleteSerialNo(serialNo) {
    var serialNoQtySum = getSerialNoQtySum();
    var id = serialNo.replace(/ /g, '');
    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: serialNo,
        Quantity: serialNoQtySum,
        QuantityOld: 0,
        QuantityNew: $("#serialNoQty-" + id).val(),
        DateDueNew: $("#IdentSerialDateDue").val() === "true" ? serialNoDateDue : null,
        DateDue: $("#IdentSerialDateDue").val() === "true" ? serialNoDateDue : null,
        Type: $("#serialNoType-0").val(),
        SNWOType: "PP",
        Package: "",
        PackQty: 0,
        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) {
            if ($("#IdentSerialNoType").val() === "P") {
                $("#serialNoQty-" + serialNo).val(0);
                $("#savedSerialNoQty-" + serialNo).val(0);
            } else {
                $("#tr-serial-" + serialNo).remove();
            }

            var serialNoQtySum = getSerialNoQtySum();
            checkSerialNumberQtySum(serialNoQtySum);
        }
    });
}

async function deleteAll() {
    var data = {
        AcKey: $("#AcKey").val(),
        AnNo: $("#IdentAnNo").val(),
        Ident: $("#identSerialNoIdent").val(),
        Type: $("#serialNoType-0").val(),
        SNWOType: "PP",
        SNType: $("#IdentSerialNoType").val()
    };

    await fetch("DeleteAllSerialNoByAcKey", {
        method: "POST",
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    }).then((response) => response.json()
    ).then((data) => {
        if (data && data === true) {
            if ($("#IdentSerialNoType").val() === "P") {
                $(".serialNoQty").val(0);
                $(".savedSerialNoQty").val(0);
            } else {
                $('#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();
        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: $("#ConfirmLoc").val(),
                                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(data) {
    if (data) {
        var qtyK = 0;
        var qtyO = 0;
        var qtyP = 0;
        for (var i = 0; i < data.length; i++) {
            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-0").val() == "X") {
            $("#finished").val(qtyK);
            $("#waste").val(qtyO);
            $("#scrap").val(qtyP);
        }
    } else {
        var serialNoQtySum = 0;
        var $qtyElements = $(".serialNoQty");
        if ($qtyElements && $qtyElements.length) {
            for (var i = 0; i < $qtyElements.length; i++) {

                serialNoQtySum = serialNoQtySum + toNumber($qtyElements[i].value);
            }
        }
        return toNumber(serialNoQtySum);
    }
}
