var globalProcessingParams;
var globalProcessingLoc;
var globalProcessingUrls;
var globalProcessingPermissions;
var activeOperations;

function initializeProcessingSvc(params, localizations, urls, permissions) {
    globalProcessingParams = params;
    globalProcessingLoc = localizations;
    globalProcessingUrls = urls;
    globalProcessingPermissions = permissions;
    workersArray = JSON.parse(globalProcessingParams.workersList);

    if (params.status === "Z") {
        $('.add-material-button').prop("disabled", true);
        $('.add-operation-button').prop("disabled", true);
        $('.finish-all-button').prop("disabled", true);
    }

    if (globalProcessingParams.itemType === "S") {
        initializeOperations();
    }
    else {
        initializeMaterials();
    }
}

function initializeOperations() {
    var fromDailyPlan = localStorage.getItem('WoFromDailyPlanSVC');
    activeOperations = localStorage.getItem('ActiveWorkOrdersSVC');

    $("#active-operations").prop('checked', function () {
        return activeOperations === "true"
    });

    $('#active-operations').on('change', function () {
        activeOperations = $(this).prop('checked') ? "true" : "false";
        $.fn.dataTable.reload($itemsTable);
    });

    $itemsTable = $('#mainGridProcessing');
    var itemsTable = $itemsTable.DataTable({
        initComplete: function () {
            var api = this.api();
            api.column(2).visible(false);
            api.column(4).visible(fromDailyPlan === "true" ? true : false);
            api.column(5).visible(fromDailyPlan === "true" ? true : false);
        },
        ajax: {
            url: $itemsTable.attr('data-url'),
            data: function (d) {
                d.Key = $("#AcKey").val();
                d.ItemType = globalProcessingParams.itemType;
                d.DataFromDailyPlan = fromDailyPlan;
                d.ActiveWorkOrders = activeOperations;
                d.Resources = $("#ResursID").val();
                d.ProductionType = globalProcessingParams.prodType;
            }
        },
        columns: [
            {
                class: 'border-bottom',
                orderable: false,
                render: function (data, type, full) {
                    var hidden = full.WoExOperRegCount == "0" ? 'hidden' : '';
                    return type === 'display' ?
                        '<div class="margin-top-10" style="height:40px">' +
                        '<span class="m-r-xxs"><i class="fa fa-hashtag fa-lg"></i> </span> <span style="font-size: medium">' + full.AnNo + '</span>' +

                        '<a id="operMat" class="far fa-newspaper fa-2x text-muted clickable-icon pull-right text-default m-l-sm" href="#" data-url="' + globalProcessingUrls.operMatURL +
                        '       " role="button" data-original-title="' + globalProcessingLoc.materialsForOperation + '" data-toggle="popover"  data-no="' + full.AnNo + '"></a>' +

                        '   <div class="pulsating-circle pull-right m-t-xs ' + hidden + '" data-toggle="popover"  data-placement="bottom" data-url="' + globalProcessingUrls.operRegURL +
                        '       " data-original-title="' + globalProcessingLoc.workRegistration + '" data-no="' + full.AnNo + '" > ' +
                        '   </div > ' +

                        '</div >' : data;
                }
            },
            {
                data: "IdentDescr",
                name: "IdentDescr",
                className: "dt-body-left",
                render: function (data, type, full) {
                    let workerIcons = getWorkerIcons(full.AcWorkers, full.AcKey, null, full.WoExItemQId, full.WoExItemResourceQId, full.Date, full.AnNo, globalProcessingParams.status );

                    return type === 'display' ?
                        '<div class="margin-top-10">' +
                        '   <div>' +
                        '       <span class="card-caption" data-toggle="tooltip" data-original-title="' + data + '"> ' + data + '</span>' +
                        '   </div>' +
                        '</div >' +
                        `<div id="operWorker" data-info="` + full.AnNo + `" style="height:50px">` + workerIcons + `</div>`: data;
                }
            },

            {
                data: "ResursID",
                name: "ResursID",
                className: "card-label",
                render: function (data, type, full) {
                    return type === 'display' ?
                        '<h3 class="card-header text-success">' +
                        '<span class="card-caption" data-toggle="tooltip"  data-original-title="' + data + ' - ' + full.ResourceName + '" >' +
                        '<i class="fas fa-cogs"></i> ' + data + ' - ' + full.ResourceName +
                        '</span>' +
                        '</h3 > ' : data;
                }
            },
            {
                data: "AcKeyDisplay",
                name: "AcKeyDisplay",
                className: "dt-body-left",
                render: function (data, type, full) {
                    return type === 'display' ?
                        '<span class="m-r-xxs"> <i class="fa fa-hashtag"></i> </span> <span>' + full.DPKeyView + '</span>' : data;
                }
            },
            {
                data: "ShiftName",
                name: "ShiftName",
                render: function (data, type, full) {
                    return type === 'display' ?
                        '<span class="m-r-xxs"><i class="fad fa-sync-alt"></i></span> <span>' + data + '</span>' : data;
                }
            },
            {
                data: "StartEnd",
                name: "StartEnd",
                render: function (data, type, full) {
                    return type === 'display' ?
                        '<span class="m-r-xxs"> <i class="far fa-clock"></i> </span> <span>' + data + '</span>' : data;
                }
            },
            {
                data: 'CompletedPrcTime',
                render: function (data, type, full) {

                    const prc = isNaN(round(full.CompletedPrcTime, 2)) ? 0 : round(full.CompletedPrcTime, 2).toString().replace('.', ',');
                    const done = isNaN(round(full.DoneTime, 2)) ? 0 : round(full.DoneTime, 2).toString().replace('.', ',');
                    const plan = isNaN(round(full.PlanTime, 2)) ? 0 : round(full.PlanTime, 2).toString().replace('.', ',');

                    const color = full.IssueFinished == 'Y' ? "bg-c-red" : data >= 100 ? "bg-c-green" : "bg-c-yellow"
                    const value = data > 100 ? 100 : data
                    return type === 'display' ?
                        '<div class="progress-card">' +
                        '<div class="progress">' +
                        '    <div class="progress-bar ' + color + '" style="width:' + value + '%" aria-valuenow="' + data + '" aria-valuemin="0" aria-valuemax="100"></div>' +
                        '</div>' +
                        '</div>' +
                        '<span>' + globalProcessingLoc.nonchargeableCaption + ' (' + prc + '%)</span>' +
                        '<span class="pull-right">' + done + '/' + plan + ' ' + full.UM + '</span>' : data;
                }
            },
            {
                data: 'CompletedPrcQty',
                render: function (data, type, full) {
                    var color = full.IssueFinished == 'Y' ? "bg-c-red" : data >= 100 ? "bg-c-green" : "bg-c-yellow"
                    var value = data > 100 ? 100 : data
                    return type === 'display' ?
                        '<div class="progress-card">' +
                        '<div class="progress">' +
                        '    <div class="progress-bar ' + color + '" style="width:' + value + '%" aria-valuenow="' + data + '" aria-valuemin="0" aria-valuemax="100"></div>' +
                        '</div>' +
                        '</div>' +
                        '<span>' + globalProcessingLoc.billableCaption + ' (' + round(full.CompletedPrcQty, 2).toString().replace('.', ',') + '%)</span>' +
                        '<span class="pull-right">' + round(full.DonePcs, 2).toString().replace('.', ',') + '/' + round(full.PlanPcs, 2).toString().replace('.', ',') + ' ' + full.UM + '</span>' : data;
                }
            }
        ],
        createdRow: function (row, data, dataIndex) {
            $(row).css('cursor', 'pointer');
            $(row).attr('id', 'row-' + dataIndex);
        },
        drawCallback: function () {
            $("[data-toggle='tooltip']").tooltip({
                container: 'body'
            }),
                $("[data-toggle=popover]").popover({
                    html: true,
                    container: "body",
                    trigger: 'hover',
                    placement: 'auto',
                    content: function () {
                        let id = $(this).attr('id');
                        $.ajax({
                            url: $(this).attr('data-url'),
                            type: 'POST',
                            async: false,
                            data: {
                                Key: $("#AcKey").val(),
                                No: $(this).attr('data-no'),
                                ItemType: ""
                            },
                            success: function (response) {
                                if (id == 'operMat') {
                                    getOperMatTable(response);
                                } else {
                                    getOperRegTable(response);
                                }
                            }
                        });

                        return $('#operPopover').html();
                    }

                }).click(function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                });
        }

    }).on('click', 'tr', function () {
        if (!globalProcessingPermissions.canInputCompletedWork)
            return;

        let data = itemsTable.row($(this)).data();
        let continueUrl = "InputCompletedWork?key=" + data.AcKey + '&anQId=' + data.WoExItemResourceQId + '&cId=' + (fromDailyPlan == 'true' ? data.QId : '0');

        showFinishedOperationModal(data, globalProcessingParams.status, continueUrl, globalProcessingLoc.operationCompleted);
    });

    $("select").off("change.tableReload");
    $("select").on("change.tableReload", function (e) {
        $.fn.dataTable.reload($itemsTable);
    });

    $('#options').on("click", function () {

        $('#sideNavBar>.tab-pane').removeClass("active");
        $('#sideNavBar>.nav>.nav-item').removeClass("active");
        $('#sideNavBar>#item-options').addClass("fade").addClass("in").addClass("active");

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

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

    $('.btn-back-to-menu').on("click", function () {

        $(".btn.btn-close-side-panel").toggleClass("hidden");
        $(".btn.btn-back-to-menu").toggleClass("hidden");

        $('#sideNavBar>.tab-pane').removeClass("active");
        $('#sideNavBar>.nav>.nav-item').removeClass("active");
        $('#sideNavBar>#item-options').addClass("fade").addClass("in").addClass("active");

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

    $('.selectResurs').on("click", function () {

        $('#sideNavBar>.tab-pane').removeClass("active");
        $('#sideNavBar>.nav>.nav-item').removeClass("active");
        $('#sideNavBar>#resurs').addClass("fade").addClass("in").addClass("active");

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

    $('.filter-list-item').on("click", function () {
        var selectedValues = [];
        var selectedText = [];

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

        var parent = $(this).parent().attr('id')

        $("#" + parent + " .filter-list-item.active").each(function (index) {
            selectedValues.push($(this).data("value"));
            selectedText.push($(this).data("display"));
        });

        var control = $(this).parent().data('control')
        $(control).val(selectedText);
        $(control).data('value', selectedValues)

        var selRes = $("#ResursID option:selected").map(function () {
            return $(this).text().trim();
        }).get().join(',');

        selRes == "" ? selRes = $("#ResursID").attr("title") : selRes;
        $("#mResursID").val(selRes);

        $(control).trigger("change");
    });

    var selRes = $("#ResursID option:selected").map(function () {
        return $(this).text().trim();
    }).get().join(',');

    selRes == "" ? selRes = $("#ResursID").attr("title") : selRes;
    $("#mResursID").val(selRes);

    $('#work-history').on("click", function () {
        var caption = $("#work-history").find("h3").text();
        $("#tabCaption>span").text(caption);

        $(".btn.btn-close-side-panel").toggleClass("hidden");
        $(".btn.btn-back-to-menu").toggleClass("hidden");

        InitWoExOperWork();
    });
};

function initializeMaterials() {
    var fromDailyPlan = globalProcessingParams.prodType === "MF" ? localStorage.getItem('WoFromDailyPlan') : "false";

    $itemsTable = $('#mainGridProcessing');
    var itemsTable = $itemsTable.DataTable({
        ajax: {
            url: $itemsTable.attr('data-url'),
            data: function (d) {
                d.Key = $("#AcKey").val();
                d.ItemType = globalProcessingParams.itemType;
                d.DataFromDailyPlan = fromDailyPlan;
            }
        },
        columns: [
            {
                class: 'border-bottom',
                data: function (data) {
                    var image = data.Picture !== '' ? " <img style='max-width:100%; max-height:150px'  src='" + data.Picture + "' />" : "<i class='fal fa-image fa-3x text-muted' style='opacity:0.5'></i>";
                    return "<span style='width:100rem;position: relative;text-align: center;vertical-align: middle;display: table-cell;height: 150px;'>" + image + "</span>";
                },
                orderable: false,
                render: function (data) {
                    return data;
                }
            },
            {
                data: "IdentDescr",
                name: "IdentDescr",
                className: "dt-body-left",
                render: function (data, type, full) {
                    return type === 'display' ?
                        '<div class="margin-top-10">' +
                        '   <div>' +
                        '       <span class="card-caption"  data-toggle="tooltip"  data-original-title="' + data + '">' + data + '</span>' +
                        '</div>' +
                        '</div >' : data;

                }
            },
            {
                data: "AnNo",
                name: "AnNo",
                className: "dt-body-left",
                render: function (data, type, full) {
                    return type === 'display' ?
                        '<span style="margin-right:2px"> <i class="fa fa-hashtag"></i> </span> <span>' + data + '</span>' : data;
                }
            },
            {
                data: 'CompletedPrcTime',
                render: function (data, type, full) {

                    const prc = isNaN(round(full.CompletedPrcTime, 2)) ? 0 : round(full.CompletedPrcTime, 2).toString().replace('.', ',');
                    const done = isNaN(round(full.DoneTime, 2)) ? 0 : round(full.DoneTime, 2).toString().replace('.', ',');
                    const plan = isNaN(round(full.PlanTime, 2)) ? 0 : round(full.PlanTime, 2).toString().replace('.', ',');

                    const color = full.IssueFinished == 'Y' ? "bg-c-red" : data >= 100 ? "bg-c-green" : "bg-c-yellow"
                    const value = data > 100 ? 100 : data
                    return type === 'display' ?
                        '<div class="progress-card">' +
                        '<div class="progress">' +
                        '    <div class="progress-bar ' + color + '" style="width:' + value + '%" aria-valuenow="' + data + '" aria-valuemin="0" aria-valuemax="100"></div>' +
                        '</div>' +
                        '</div>' +
                        '<span>' + globalProcessingLoc.nonchargeableCaption + ' (' + prc + '%)</span>' +
                        '<span class="pull-right">' + done + '/' + plan + ' ' + full.UM + '</span>' : data;
                }
            },

            {
                data: 'CompletedPrcQty',
                render: function (data, type, full) {
                    var color = full.IssueFinished == 'Y' ? "bg-c-red" : data >= 100 ? "bg-c-green" : "bg-c-yellow"
                    var value = data > 100 ? 100 : data
                    return type === 'display' ?
                        '<div class="progress-card">' +
                        '<div class="progress">' +
                        '    <div class="progress-bar ' + color + '" style="width:' + value + '%" aria-valuenow="' + data + '" aria-valuemin="0" aria-valuemax="100"></div>' +
                        '</div>' +
                        '</div>' +
                        '<span>' + globalProcessingLoc.billableCaption + ' (' + round(full.CompletedPrcQty, 2).toString().replace('.', ',') + '%)</span>' +
                        '<span class="pull-right">' + round(full.DonePcs, 2).toString().replace('.', ',') + '/' + round(full.PlanPcs, 2).toString().replace('.', ',') + ' ' + full.UM + '</span>' : data;
                }
            }
        ],
        createdRow: function (row, data, dataIndex) {
            $(row).css('cursor', 'pointer');
        },
        drawCallback: function () {
            $("[data-toggle='tooltip']").tooltip({
                container: 'body'
            });
        }
    })

    itemsTable.on('click', 'tr', function () {
        let data = itemsTable.row($(this)).data();
        let continueUrl = "IssuingMaterial?key=" + data.AcKey + '&no=' + data.AnNo;

        showFinishedOperationModal(data, globalProcessingParams.status, continueUrl, globalProcessingLoc.materialCompleted);
    });
};

function getOperMatTable(response) {
    $("#popoverTable").empty();
    var trHTML = '';
    $.each(response.data, function (i, item) {
        var image = item.Picture !== '' ? " <img src='" + item.Picture + "' />" : "<i class='fal fa-image fa-3x text-muted' style='opacity:0.5'></i>";

        trHTML +=
            '<tr>' +
            '   <td style="width:100px;max-height: 50px;"> <span style="position: relative; text-align: center; vertical-align: middle; display: table-cell; height: 50px;">' +
                    image +
            '   </td>' +
            '   <td style="min-width:300px">' +
            '       <div class="margin-top-10">' +
            '           <label class="control-label">' + globalProcessingLoc.materialCaption + '  <i class="fa fa-hashtag"></i><span>' + item.AnNo + '</span></label>' +
            '           <div>' +
            '               <span style="font-size: 14px; display: inline-block; overflow:hidden; text-overflow: ellipsis;">' + item.IdentDescr + '</span>' +
            '           </div>' +
            '       </div >' +
            '       <div class="margin-top-10">' +
            '       <span>' + item.Status + ' (' + round(item.CompletedPrcQty, 2) + '%)</span>' +
            '       <span class="pull-right">' + round(item.DonePcs, 2) + '/' + round(item.PlanPcs, 2) + ' ' + item.UM + '</span>' +
            '       <progress value = ' + item.CompletedPrcQty + ' max = "100" style = "width: 100%" ></progress >' +
            '           </div>' +
            '   </td>' +
            '</tr>';
    });
    $('#popoverTable').append(trHTML);
}

function openAddWorkersModal(acKey, woExQId, itemQId, itemResourceQId, date, anNo) {
    event.preventDefault();
    event.stopPropagation();

    if (anNo) {
        AWMSelectedRow = $(`[data-info="${anNo}"]`).closest('tr').attr('id');
    } else {
        AWMSelectedRow = $(`[data-info="${acKey}"]`).closest('tr').attr('id');
    }

    AWMSelectedAcKey = acKey;
    AWMSelectedWoExQId = woExQId;
    AWMSelectedItemQId = itemQId;
    AWMSelectedItemResourceQId = itemResourceQId;
    AWMSelectedDate = convertToISOString(date);
    AWMDate = date;
    AWMAnNo = anNo;

    openModal('add-workers-modal');
}

function convertToISOString(value) {
    if (typeof value === 'string') {
        if (value.startsWith('/Date(') && value.endsWith(')/')) {
            const timestamp = parseInt(value.substring(6, value.length - 2));
            return new Date(timestamp).toISOString();
        } else {
            return moment(value, 'DD.MM.YYYY').toDate().toISOString();
        }
    } else {
        return null;
    }
}

function saveOperation(validate) {

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

    if (validate) {
        var qty = $("#qty").val();
        var worker = $('#selectWorker :selected').text();
        var requiedText = "";
        if (worker === "")
            requiedText = $("#requiedWorker").val();
        else
            if (qty === 0 || qty === "")
                requiedText = $("#requiedQty").val();


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

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

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

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

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

            } else {

                let errorText = response.Error;

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

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

function InitWoExOperWork() {
    var decPlaces = $("#WoExDecPlacesProd").val();

    $dataTable = $('#woExOperWork');

    if ($.fn.dataTable.isDataTable('#woExOperWork')) {
        $.fn.dataTable.reload($dataTable);
    }
    else {
        $dataTable.DataTable({
            responsive: true,
            serverSide: false,
            scroller: false,
            responsive: true,
            paging: false,
            info: false,
            sScrollX: "100%",
            scrollX: true,
            initComplete: function () {
                $('.dataTables_scrollBody').css('max-height', '70vh');
                $('.dataTables_scrollBody').css('height', '70vh');
            },
            ajax: {
                url: $dataTable.attr('data-url'),
                data: function (d) {
                    d.Key = $("#AcKey").val();
                    d.No = $("#AnNo").val();
                    d.ResursID = $("#ResursID").val();
                    d.ProductionType = "DN";
                }
            },
            columns: [

                { data: "Worker", name: "Worker" },
                { data: "KeyView", name: "KeyView" },
                {
                    data: "Ident", name: "Ident",
                    render: function (data, type, full) {
                        return data +
                            '<span class="text-muted m-r-sm" style="display:block;font-style:italic;">' + full.Descr + '</span>';
                    }

                },
                { data: "PlanQty", name: "PlanQty", className: 'dt-body-center' },
                {
                    name: "StatePcs",
                    render: function (data, type, full) {
                        return '<div style="min-width:max-content" ><span class="label-success m-r-sm" style="padding:5px; border-radius:10px"><i class="fas fa-thumbs-up m-r-sm"></i>' + round(full.GoodPcs, decPlaces).toString().replace('.', ',') + '</span>' +
                            '<span class="label-primary m-r-sm" style="padding:5px; border-radius:10px"><i class="fas fa-wrench m-r-sm"></i>' + round(full.RepairQty, decPlaces).toString().replace('.', ',') + '</span>' +
                            '<span class="label-danger" style="padding:5px; border-radius:10px"><i class="fas fa-times m-r-sm"></i>' + round(full.ScrapPcs, decPlaces).toString().replace('.', ',') + '</span></div>';

                    }
                }
            ]
        });

        $("select").off("change.tableReload");
        $("select").on("change.tableReload", function (e) {
            var str = '';

            $("option:selected", this).each(function () {
                str += $(this).val() + " ";
            });

            if (str.length === 0) {
                $("option[value='']", this).attr('selected', true);
                $(this).parent().find('ul>li:first').addClass('selected');
                $(this).parent().find('ul>li:first>a').addClass('selected');


            } else {
                $("option[value='']", this).attr('selected', false);
                $(this).parent().find('ul>li:first').removeClass('selected');
                $(this).parent().find('ul>li:first>a').removeClass('selected');
            }

            $.fn.dataTable.reload($dataTable);
        });
    }
}


