function prevWorkOrder(acKey) {
    let url = window.location.href;
    let splitted = url.split('key=');
    let prevUrl = splitted[0];

    $(".prev-next-key-display .fa-chevron-left").removeClass("fa-chevron-left").addClass("fa-spinner").addClass("fa-spin");
    window.location.href = prevUrl + "key=" + acKey;
}

function nextWorkOrder(acKey) {
    let url = window.location.href;
    let splitted = url.split('key=');
    let nextUrl = splitted[0];

    $(".prev-next-key-display .fa-chevron-right").removeClass("fa-chevron-left").addClass("fa-spinner").addClass("fa-spin");
    window.location.href = nextUrl + "key=" + acKey;
}

function displayWarehouse(warehouseId) {
    var containerId = '#select2-' + warehouseId + '-container';
    var warehouse = $(containerId).text();

    if (warehouse.indexOf(",") > -1) {
        warehouse = warehouse.split(", ")[0];
        $(containerId).text(warehouse);
    }
}

function checkStatusAndContinue(statusDisplay, status, continueUrl, changeStatusUrl, acKey, prodType) {
    if (prodType === "SE" || status === 'R' || status === 'D' || status === 'E') {
        window.location.href = continueUrl;
    } else {
        showChangesNotAllowedModal(statusDisplay, continueUrl, changeStatusUrl, acKey);
    }
}

function showChangesNotAllowedModal(statusDisplay, continueUrl, changeStatusUrl, acKey) {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "alert",
        text: $("#WOChangesNotAllowedLoc").val().replace("{0}", statusDisplay),
        buttons: [
            {
                icon: 'fa fa-times',
                text: $("#NoLoc").val(),
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: $("#ConfirmLoc").val(),
                action: function () {
                    changeWOStatus(changeStatusUrl, acKey, 'R', continueUrl);
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function showFinishedOperationModal(data, statusWO, continueUrl, textMessage) {
    if (data.IssueFinished != 'Y') {

        if (statusWO == 'Z') {
            openRN(data.AcKey, globalProcessingParams.statusDisplay, globalProcessingUrls.openWOURL, continueUrl);
        }
        else {
            window.location.href = continueUrl;
            return;
        }
    } else {

        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            id: "displayPopupSuccessModal",
            type: "question",
            text: textMessage,
            buttons: [
                {
                    icon: 'fa fa-times',
                    text: $("#NoLoc").val(),
                    closeOnAction: true,
                    type: 'ghost'
                },
                {
                    icon: 'fa fa-check',
                    text: $("#ConfirmLoc").val(),
                    closeOnAction: true,
                    type: 'primary',
                    action: function () {
                        openFinishedOperation(data, continueUrl);
                    }
                }
            ]
        });
        customModalForMobile(globalProcessingParams.isMobile);
    }
}

function openFinishedOperation(data, continueUrl) {


    console.log(data);

    var d = {
        AcKey: data.AcKey,
        AnNo: data.AnNo,
        QId: data.WoExItemQId,
        ResourceQId: data.WoExItemResourceQId,
        Finished: "N"
    };

    console.log(d);
    //return;

    $.post(globalProcessingUrls.setOperationFinishedURL, d)
        .done(function (response) {
            if (response.Success) {
                window.location.href = continueUrl;

            } else {

                let errorText = response.Error;

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

            }
        });

}

function changeWOStatus(changeStatusUrl, key, status, continueUrl) {
    $.ajax({
        cache: false,
        type: "POST",
        url: changeStatusUrl,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            key: key,
            status: status
        }),
        success: function (response) {
            if (response.Success) {
                if (continueUrl) {
                    window.location.href = continueUrl;
                }
                else {
                    $.fn.dataTable.reload($mainGridTable);
                    closeInfoCard();
                }
            }
        },
        error: function (error) {
            console.error(error);
        }
    });
}

 function openPdfPreview(url, signature = false, signatureLoaded = false) {
    if (signature) {
        openSignatureForm(() => { openPdfPreview(url, false, true); });
        return;
    }

    if (signatureLoaded) {
        let signatureData = clientSignature.replace("data:image/png;base64,", "");

        if ($("#pdfPanel").hasClass("open") && $("#pdfPanel").find(".side-panel-content embed").attr("src") === url) {
            closeSidePanel($("#pdfPanel"));
            $("#pdfPanel").find(".side-panel-content").html("");
            return;
        }

        $("#pdfPanel").find(".side-panel-content").html('<div class="side-panel-loader side-panel-loader-media"><i class="fa fa-spinner fa-spin fa-x4"></i></div><embed width="100%" height="100%" />');

        fetch(url, {
            method: "POST",
            headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
            body: JSON.stringify({ signature: signatureData })
        }).then((response) => response.json()
        ).then(async (response) => {
            if (response && response.Error) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: response.Error,
                    buttons: [
                        {
                            icon: 'fa fa-times',
                            text: globalWorkOrderLoc.confirm,
                            closeOnAction: true,
                            action: function () {
                                closeSidePanel($("#pdfPanel"));
                            },
                            type: 'primary'
                        }
                    ]
                });
            } else {
                var byte = base64ToArrayBuffer(response.File ? response.File : response);
                var blob = new Blob([byte], { type: response.ContentType ? response.ContentType : "application/pdf" });
                $("#pdfPanel").find(".side-panel-content").html('<div class="side-panel-loader side-panel-loader-media"><i class="fa fa-spinner fa-spin fa-x4"></i></div><embed src="' + URL.createObjectURL(blob) + '#toolbar=1' + '" width="100%" height="100%" onLoad="$(this).prev().addClass(\'hidden\')" />');
            }
        });

        openSidePanel($("#pdfPanel"));

        return;
    }

    loadPdfPanelContentPAAS($("#pdfPanel"), url, true);
}

function decimalToTime(decimalHours) {
    let hours = Math.floor(decimalHours);
    let minutes = Math.floor((decimalHours - hours) * 60);
    let seconds = Math.round(((decimalHours - hours) * 60 - minutes) * 60);

    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}

function saveWorkOrderNote(url) {
    $.ajax({
        cache: false,
        type: "POST",
        url: url,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            key: $('#NoteKey').val(),
            note: $('#note-input').val()
        }),
        success: function (response) {
            $('#work-order-note-modal').modal('hide');
        },
        error: function (error) {
            console.error(error);
        }
    });
}

function loadWorkOrderNote(url, acKey) {
    $.ajax({
        cache: false,
        type: "GET",
        url: url,
        data: { key: acKey },
        async: false,
        success: function (response) {
            $('#NoteKey').val(acKey);
            $('#note-input').val(response.Content);

            $('#work-order-note-modal').modal('show');
        },
        error: function (error) {
            console.error(error);
        }
    });
}

function confirmMatMass(url, acKey) {
    swapLoadingIcon(true, "finish-all-button", "fas fa-tasks");

    $.ajax({
        cache: false,
        type: "POST",
        url: url,
        data: { acKey: acKey },
        success: function (response) {
            if (response.Success) {
                $.fn.dataTable.reload($itemsTable);
            } else {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: false,
                    type: "alert",
                    text: response.Errors.join('<br>'),
                    closeOtherModals: false,
                    buttons: [
                        {
                            text: globalProcessingLoc.ok,
                            icon: 'fa fa-check',
                            closeOnAction: true,
                            type: 'primary'
                        },
                    ]
                });
            }

            swapLoadingIcon(false, "finish-all-button", "fas fa-tasks");
        },
        error: function (error) {
            console.error(error);
            swapLoadingIcon(false, "finish-all-button", "fas fa-tasks");
        }        
    });

    customModalForMobile(globalProcessingParams.isMobile);
}

function parseUsedTime(value) {
    if (value.includes(':')) {
        const [hours, minutes, seconds] = value.split(':').map(Number);
        return hours + minutes / 60 + seconds / 3600;
    } else if (value.includes(',')) {
        return parseFloat(value.replace(',', '.'));
    } else {
        return 0;
    }
}

function reloadDataTable(tableId) {
    $.fn.dataTable.reload($("#" + tableId));
}

function addOnDP(url, WOKey, DPKey, addOnInWork, woExItemResourceQId) {

    console.log(url, WOKey, DPKey, addOnInWork, woExItemResourceQId);

    $.ajax({
        cache: false,
        type: "POST",
        url: url,
        data: {
            WoKey: WOKey,
            DPKey: DPKey,
            WoExItemResQid: woExItemResourceQId,
            addOnLastInWork: addOnInWork
        },
        success: function (response) {
            $('#add-on-dp-modal').modal('hide');

            if (woExItemResourceQId == 0)
                reloadDataTable('mainGrid')
            else
                reloadDataTable('mainGridProcessing');            
        },
        error: function (error) {
            console.error(error);
        }
    });


}