$(document).ready(function () {
    $('#add-operation-modal').on('shown.bs.modal', function () {
        loadNewPosition();
    });

    $('#save-operation-btn').click(function () {
        saveNewOperation();
    });

    $('#add-operation-modal').on('hidden.bs.modal', function () {
        clearOperationSelections();
    });

    $('#tpr_dQuantity').click(function () {
        var quantity = $('#tpr-quantity');
        var currentValue = parseInt(quantity.val(), 10);

        if (currentValue > 0) {
            quantity.val(currentValue - 1);
        }
    });

    $('#tpr_iQuantity').click(function () {
        var quantity = $('#tpr-quantity');
        var currentValue = parseInt(quantity.val(), 10);
        quantity.val(currentValue + 1);
    });

    $('#tsu_dQuantity').click(function () {
        var quantity = $('#tsu-quantity');
        var currentValue = parseInt(quantity.val(), 10);

        if (currentValue > 0) {
            quantity.val(currentValue - 1);
        }
    });

    $('#tsu_iQuantity').click(function () {
        var quantity = $('#tsu-quantity');
        var currentValue = parseInt(quantity.val(), 10);
        quantity.val(currentValue + 1);
    });

    $('#selected-operation').change(function () {
        let selectedOption = $(this).find('option:selected');
        let description = selectedOption.data('name');
        $('#description-operation').val(description);
    });

    $('#selected-resource').change(function () {
        let selectedOption = $(this).find('option:selected');
        let description = selectedOption.data('name');
        $('#description-resource').val(description);
    });

    $('#selected-tool').change(function () {
        let selectedOption = $(this).find('option:selected');
        let description = selectedOption.data('name');
        let table = selectedOption.data('table');
        $('#table').val(table);
        $('#description-tool').val(description);
    });
});

function loadNewPosition() {
    $.ajax({
        type: 'GET',
        url: $('#GetNewPositionUrl').val(),
        data: {
            acKey: globalProcessingParams.acKey
        },
        success: function (response) {
            $('#position').val(response);
        },
        error: function (error) {
            console.log(error);
        }
    });
}

function clearOperationSelections() {
    $('#quantity').val(0);
    $('#position, #description-operation, #description-tool').val('');
    $('#description-resource').val('RI');
    $("#selected-operation").prop('selectedIndex', 0);
    $("#selected-resource").prop('selectedIndex', 0);
    $("#selected-tool").prop('selectedIndex', 0);
    $('.selectpicker').selectpicker('refresh');
}

function saveNewOperation() {
    swapLoadingIcon(true, "save-operation-btn", "fa fa-check");

    let resource = [{
        qty1: $('#tpr-quantity').val(),
        qty2: $('#tsu-quantity').val(),
        resursID: $('#selected-resource').val()
    }];

    let data = {
        anNo: $('#position').val(),
        um: $('#measurementUnit').val(),
        umTime: $('#umTime').val(),
        ident: $('#selected-operation').val(),
        descr: $('#description-operation').val(),
        woExItemResources: resource,
        acKey: globalProcessingParams.acKey,
        operationType: 'D'
    };

    $.ajax({
        cache: false,
        type: "POST",
        url: $('#AddNewOperationUrl').val(),
        contentType: 'application/json',
        data: JSON.stringify(data),
        success: function (response) {
            if (response && response.WoExItemResources[0] && $("#selected-tool").val()) {
                saveOperationTool(response.WoExItemResources[0].QId);
            } else {
                swapIconsAndClose();
            }
        },
        error: function (error) {
            console.error(error);
        }
    });
}

function saveOperationTool(QId) {
    let formData = new FormData();
    formData.append('toolId', $('#selected-tool').val());
    formData.append('name', $('#description-tool').val());
    formData.append('acKey', globalProcessingParams.acKey);
    formData.append('table', $('#table').val());
    formData.append('resursQId', QId);

    $.ajax({
        cache: false,
        type: "POST",
        url: $('#AddNewToolUrl').val(),
        processData: false,
        contentType: false,
        data: formData,
        success: function () {
            swapIconsAndClose();
        },
        error: function (error) {
            console.error(error);
        }
    });
}

function swapIconsAndClose() {
    $.fn.dataTable.reload($itemsTable);
    $('#add-operation-modal').modal('hide');
    swapLoadingIcon(false, "save-operation-btn", "fa fa-check");
}
