798 lines
29 KiB
JavaScript
798 lines
29 KiB
JavaScript
$(document).ready(function () {
|
|
console.log("parts.js caricato correttamente");
|
|
|
|
// ===================
|
|
// CONFIGURAZIONE API Remove.bg
|
|
// ===================
|
|
const REMOVE_BG_API_KEY = "E85XGT5heTBUtWsf9zMLM7cg"; // Sostituisci con la tua chiave API
|
|
|
|
// ===================
|
|
// GLOBAL STATE
|
|
// ===================
|
|
let photoData = {
|
|
naturalWidth: 0,
|
|
naturalHeight: 0,
|
|
displayWidth: 0,
|
|
displayHeight: 0,
|
|
scale: 1,
|
|
};
|
|
|
|
let photoMarkers = {};
|
|
let selectedPartNumber = null;
|
|
let descriptionPosition = { x: 10, y: 10 };
|
|
let hasDescriptions = false;
|
|
|
|
// Verifica inizializzazione del pulsante
|
|
console.log(
|
|
"Verifica pulsante #removeBackgroundBtn:",
|
|
$("#removeBackgroundBtn").length,
|
|
);
|
|
|
|
// ===================
|
|
// POPUP HANDLING
|
|
// ===================
|
|
const partsButtons = document.querySelectorAll(".parts-btn");
|
|
const partsModal = document.getElementById("partsModal");
|
|
|
|
partsButtons.forEach((button) => {
|
|
button.addEventListener("click", function () {
|
|
console.log("Pulsante Parts cliccato");
|
|
const iddatadb = $(this).data("iddatadb");
|
|
const rowIndex = $(this).data("row");
|
|
const importRef = $("table tbody tr")
|
|
.eq(rowIndex)
|
|
.find("td")
|
|
.eq(1)
|
|
.text();
|
|
const description =
|
|
$("table tbody tr").eq(rowIndex).find("td").eq(2).text() ||
|
|
"Sconosciuto";
|
|
|
|
$("#trfHeader").text(`${iddatadb} - ${importRef} - ${description}`);
|
|
$("#partsModal").data("iddatadb", iddatadb);
|
|
|
|
loadPhoto(iddatadb);
|
|
loadExistingParts(iddatadb);
|
|
|
|
if (partsModal) {
|
|
const modal = new bootstrap.Modal(partsModal);
|
|
modal.show();
|
|
console.log("Modale aperto");
|
|
} else {
|
|
console.error("Modal Parts non trovato");
|
|
}
|
|
});
|
|
});
|
|
|
|
// ===================
|
|
// PHOTO LOADERS
|
|
// ===================
|
|
function loadPhoto(iddatadb) {
|
|
console.log("Caricamento foto per iddatadb:", iddatadb);
|
|
$.ajax({
|
|
url: "load_photo.php",
|
|
method: "GET",
|
|
data: { iddatadb: iddatadb },
|
|
success: function (response) {
|
|
console.log("Risposta load_photo.php:", response);
|
|
if (response.success) {
|
|
if (response.photos && response.photos.length > 1) {
|
|
showPhotoSelector(response.photos);
|
|
} else if (
|
|
response.photos &&
|
|
response.photos.length === 1
|
|
) {
|
|
loadSinglePhoto(response.photos[0]);
|
|
} else {
|
|
$("#samplePhoto").attr("src", "");
|
|
alert("Nessuna foto trovata per questo TRF.");
|
|
console.log("Nessuna foto trovata");
|
|
}
|
|
} else {
|
|
alert(
|
|
response.message ||
|
|
"Errore nel caricamento della foto.",
|
|
);
|
|
console.error("Errore load_photo.php:", response.message);
|
|
}
|
|
},
|
|
error: function (xhr, status, error) {
|
|
alert("Errore nel caricamento della foto: " + error);
|
|
console.error("Errore AJAX load_photo.php:", error, xhr.status);
|
|
},
|
|
});
|
|
}
|
|
|
|
function showPhotoSelector(photos) {
|
|
console.log("Mostra selettore foto:", photos);
|
|
const selectorContainer = $("#photoSelectorContainer");
|
|
selectorContainer.empty();
|
|
|
|
const selector = $('<select id="photoSelector"></select>');
|
|
photos.forEach((photo, index) => {
|
|
const option = $("<option></option>")
|
|
.val(photo)
|
|
.text(`Photo ${index + 1}`);
|
|
if (photo.includes("/")) {
|
|
const photoName = photo.split("/").pop();
|
|
option.text(`Photo ${index + 1} - ${photoName}`);
|
|
}
|
|
selector.append(option);
|
|
});
|
|
|
|
selector.on("change", function () {
|
|
const selectedPhoto = $(this).val();
|
|
loadSinglePhoto(selectedPhoto);
|
|
});
|
|
|
|
selectorContainer.append(selector);
|
|
selectorContainer.show();
|
|
|
|
if (photos.length > 0) {
|
|
selector.val(photos[0]);
|
|
loadSinglePhoto(photos[0]);
|
|
}
|
|
}
|
|
|
|
function loadSinglePhoto(photoPath) {
|
|
console.log("Caricamento singola foto:", photoPath);
|
|
const img = $("#samplePhoto");
|
|
img.off("load");
|
|
img.attr("src", photoPath);
|
|
|
|
img.on("load", function () {
|
|
console.log(
|
|
"Immagine caricata, dimensioni naturali:",
|
|
img[0].naturalWidth,
|
|
img[0].naturalHeight,
|
|
);
|
|
const canvas = document.getElementById("photoCanvas");
|
|
const ctx = canvas.getContext("2d");
|
|
|
|
const naturalWidth = img[0].naturalWidth;
|
|
const naturalHeight = img[0].naturalHeight;
|
|
|
|
const parent = $(canvas).parent();
|
|
const maxW = parent.width();
|
|
const maxH = parent.height();
|
|
const scale = Math.min(maxW / naturalWidth, maxH / naturalHeight);
|
|
|
|
const displayWidth = Math.max(1, Math.round(naturalWidth * scale));
|
|
const displayHeight = Math.max(
|
|
1,
|
|
Math.round(naturalHeight * scale),
|
|
);
|
|
|
|
photoData = {
|
|
naturalWidth,
|
|
naturalHeight,
|
|
displayWidth,
|
|
displayHeight,
|
|
scale,
|
|
};
|
|
|
|
canvas.width = naturalWidth;
|
|
canvas.height = naturalHeight;
|
|
|
|
canvas.style.width = `${displayWidth}px`;
|
|
canvas.style.height = `${displayHeight}px`;
|
|
|
|
$("#markerContainer").css({
|
|
width: `${displayWidth}px`,
|
|
height: `${displayHeight}px`,
|
|
});
|
|
$("#descriptionList").css({
|
|
maxWidth: `${Math.max(200, Math.round(displayWidth * 0.35))}px`,
|
|
});
|
|
|
|
ctx.clearRect(0, 0, naturalWidth, naturalHeight);
|
|
ctx.drawImage(img.get(0), 0, 0, naturalWidth, naturalHeight);
|
|
|
|
updateMarkers();
|
|
if (hasDescriptions)
|
|
drawDescriptions(descriptionPosition.x, descriptionPosition.y);
|
|
});
|
|
|
|
img.on("error", function () {
|
|
console.error("Errore caricamento immagine:", photoPath);
|
|
alert("Errore nel caricamento dell'immagine.");
|
|
});
|
|
}
|
|
|
|
// ===================
|
|
// PARTS TABLE
|
|
// ===================
|
|
function addNewRow(nextPartNumber, isMix = false) {
|
|
const description = isMix ? "Mix" : "";
|
|
const newRow = `
|
|
<tr data-part-id="">
|
|
<td><input type="number" class="form-control form-control-sm part-number" value="${nextPartNumber || 1}" style="width: 80px;"></td>
|
|
<td><input type="text" class="form-control form-control-sm part-description" value="${description}" placeholder="Inserisci descrizione" style="width: 100%;"></td>
|
|
<td>
|
|
<button type="button" class="btn btn-success btn-sm add-row" style="padding: 0.1rem 0.3rem; font-size: 0.8rem;"><i class="fas fa-plus fa-xs"></i></button>
|
|
<button type="button" class="btn btn-primary btn-sm add-mix-row" style="padding: 0.1rem 0.3rem; font-size: 0.8rem;">M</button>
|
|
<button type="button" class="btn btn-danger btn-sm remove-row" style="padding: 0.1rem 0.3rem; font-size: 0.8rem; display: none;"><i class="fas fa-trash fa-xs"></i></button>
|
|
<span class="save-status text-success" style="display: none; margin-left: 5px;"><i class="fas fa-check fa-xs"></i></span>
|
|
<span class="save-loading text-warning" style="display: none; margin-left: 5px;"><i class="fas fa-spinner fa-spin fa-xs"></i></span>
|
|
</td>
|
|
</tr>`;
|
|
$("#partsTableBody").append(newRow);
|
|
updateRowButtons();
|
|
}
|
|
|
|
function updateRowButtons() {
|
|
const rowCount = $("#partsTableBody tr").length;
|
|
$("#partsTableBody tr").each(function () {
|
|
const $removeBtn = $(this).find(".remove-row");
|
|
if (rowCount > 1) $removeBtn.show();
|
|
else $removeBtn.hide();
|
|
});
|
|
}
|
|
|
|
$(document).on("click", ".add-row", function (e) {
|
|
e.preventDefault();
|
|
const maxPartNumber = Math.max(
|
|
...$("#partsTableBody tr")
|
|
.map(function () {
|
|
return parseInt($(this).find(".part-number").val()) || 0;
|
|
})
|
|
.get(),
|
|
);
|
|
addNewRow(maxPartNumber + 1);
|
|
updatePartsList();
|
|
});
|
|
|
|
$(document).on("click", ".add-mix-row", function (e) {
|
|
e.preventDefault();
|
|
const maxPartNumber = Math.max(
|
|
...$("#partsTableBody tr")
|
|
.map(function () {
|
|
return parseInt($(this).find(".part-number").val()) || 0;
|
|
})
|
|
.get(),
|
|
);
|
|
addNewRow(maxPartNumber + 1, true);
|
|
updatePartsList();
|
|
});
|
|
|
|
$(document).on("click", ".remove-row", function (e) {
|
|
e.preventDefault();
|
|
const $row = $(this).closest("tr");
|
|
const partId = $row.data("part-id");
|
|
|
|
if (partId !== "new" && partId !== undefined && partId !== null) {
|
|
$.ajax({
|
|
url: "delete_part.php",
|
|
method: "POST",
|
|
data: JSON.stringify({ part_id: partId }),
|
|
contentType: "application/json",
|
|
success: function (response) {
|
|
if (response.success) {
|
|
$row.remove();
|
|
updateRowButtons();
|
|
updatePartsList();
|
|
clearCanvasMarkers();
|
|
} else {
|
|
alert("Errore nell'eliminazione: " + response.message);
|
|
}
|
|
},
|
|
error: function (xhr, status, error) {
|
|
alert(
|
|
"Errore nell'eliminazione: " +
|
|
error +
|
|
". Stato: " +
|
|
xhr.status +
|
|
" - " +
|
|
xhr.responseText,
|
|
);
|
|
},
|
|
});
|
|
} else {
|
|
$row.remove();
|
|
updateRowButtons();
|
|
updatePartsList();
|
|
}
|
|
});
|
|
|
|
$(document).on("blur", ".part-description, .part-number", function () {
|
|
const $input = $(this);
|
|
const $row = $input.closest("tr");
|
|
const partNumber = $row.find(".part-number").val();
|
|
const partDescription = $row.find(".part-description").val().trim();
|
|
const $saveStatus = $row.find(".save-status");
|
|
const $saveLoading = $row.find(".save-loading");
|
|
const iddatadb = $("#partsModal").data("iddatadb");
|
|
const isMix = partDescription.startsWith("Mix") ? "Y" : "N";
|
|
|
|
const partId = $row.data("part-id") || null;
|
|
|
|
if (partDescription && iddatadb) {
|
|
$saveLoading.show();
|
|
$saveStatus.hide();
|
|
|
|
$.ajax({
|
|
url: "save_parts.php",
|
|
method: "POST",
|
|
data: JSON.stringify({
|
|
iddatadb: iddatadb,
|
|
parts: [
|
|
{
|
|
id: partId,
|
|
part_number: partNumber,
|
|
part_description: partDescription,
|
|
mix: isMix,
|
|
},
|
|
],
|
|
}),
|
|
contentType: "application/json",
|
|
success: function (response) {
|
|
if (response.success) {
|
|
$saveLoading.hide();
|
|
$saveStatus.show();
|
|
updatePartsList();
|
|
if (response.part_id) {
|
|
$row.attr("data-part-id", response.part_id);
|
|
$row.data("part-id", response.part_id);
|
|
}
|
|
setTimeout(() => $saveStatus.hide(), 2000);
|
|
} else {
|
|
alert("Errore nel salvataggio: " + response.message);
|
|
$saveLoading.hide();
|
|
}
|
|
},
|
|
error: function (xhr, status, error) {
|
|
alert("Errore nel salvataggio delle parti: " + error);
|
|
$saveLoading.hide();
|
|
},
|
|
});
|
|
}
|
|
});
|
|
|
|
function loadExistingParts(iddatadb) {
|
|
console.log("Caricamento parti esistenti per iddatadb:", iddatadb);
|
|
$.ajax({
|
|
url: "load_parts.php",
|
|
method: "GET",
|
|
data: { iddatadb: iddatadb },
|
|
success: function (response) {
|
|
console.log("Risposta load_parts.php:", response);
|
|
if (response.success) {
|
|
$("#partsTableBody").empty();
|
|
if (response.parts.length > 0) {
|
|
response.parts.forEach((part) => {
|
|
const newRow = `
|
|
<tr data-part-id="${part.id}">
|
|
<td><input type="number" class="form-control form-control-sm part-number" value="${part.part_number}" style="width: 80px;"></td>
|
|
<td><input type="text" class="form-control form-control-sm part-description" value="${part.part_description}" style="width: 100%;"></td>
|
|
<td>
|
|
<button type="button" class="btn btn-success btn-sm add-row" style="padding: 0.1rem 0.3rem; font-size: 0.8rem;"><i class="fas fa-plus fa-xs"></i></button>
|
|
<button type="button" class="btn btn-primary btn-sm add-mix-row" style="padding: 0.1rem 0.3rem; font-size: 0.8rem;">M</button>
|
|
<button type="button" class="btn btn-danger btn-sm remove-row" style="padding: 0.1rem 0.3rem; font-size: 0.8rem;"><i class="fas fa-trash fa-xs"></i></button>
|
|
<span class="save-status text-success" style="display: none; margin-left: 5px;"><i class="fas fa-check fa-xs"></i></span>
|
|
<span class="save-loading text-warning" style="display: none; margin-left: 5px;"><i class="fas fa-spinner fa-spin fa-xs"></i></span>
|
|
</td>
|
|
</tr>`;
|
|
$("#partsTableBody").append(newRow);
|
|
});
|
|
} else {
|
|
addNewRow(1);
|
|
}
|
|
updateRowButtons();
|
|
updatePartsList();
|
|
} else {
|
|
alert(
|
|
"Errore nel caricamento delle parti: " +
|
|
response.message,
|
|
);
|
|
console.error("Errore load_parts.php:", response.message);
|
|
addNewRow(1);
|
|
}
|
|
},
|
|
error: function (xhr, status, error) {
|
|
alert("Errore nel caricamento delle parti: " + error);
|
|
console.error("Errore AJAX load_parts.php:", error, xhr.status);
|
|
addNewRow(1);
|
|
},
|
|
});
|
|
}
|
|
|
|
function updatePartsList() {
|
|
$("#partsList").empty();
|
|
$("#partsTableBody tr").each(function () {
|
|
const partNumber = $(this).find(".part-number").val();
|
|
const partDescription = $(this).find(".part-description").val();
|
|
if (
|
|
partNumber &&
|
|
partDescription &&
|
|
!partDescription.startsWith("Mix")
|
|
) {
|
|
const listItem = `
|
|
<li class="list-group-item" data-part-number="${partNumber}">
|
|
${partNumber} - ${partDescription}
|
|
<button type="button" class="btn btn-success btn-sm add-to-mix-btn" style="padding: 0.1rem 0.3rem; font-size: 0.8rem;"><i class="fas fa-plus fa-xs"></i></button>
|
|
</li>`;
|
|
$("#partsList").append(listItem);
|
|
}
|
|
});
|
|
}
|
|
|
|
$(document).on("click", ".add-to-mix-btn", function () {
|
|
const $listItem = $(this).closest("li");
|
|
const partDescription = $listItem.text().split(" - ")[1].trim();
|
|
const $mixRow = $("#partsTableBody tr")
|
|
.filter(function () {
|
|
return $(this)
|
|
.find(".part-description")
|
|
.val()
|
|
.startsWith("Mix");
|
|
})
|
|
.last();
|
|
|
|
if ($mixRow.length === 0) {
|
|
alert("Crea prima una riga Mix usando il pulsante 'M'.");
|
|
return;
|
|
}
|
|
|
|
const $descriptionInput = $mixRow.find(".part-description");
|
|
let currentDescription = $descriptionInput.val().trim();
|
|
|
|
if (currentDescription === "Mix") {
|
|
currentDescription = `Mix ${partDescription}`;
|
|
} else if (!currentDescription.includes(partDescription)) {
|
|
currentDescription += ` + ${partDescription}`;
|
|
} else {
|
|
return;
|
|
}
|
|
|
|
$descriptionInput.val(currentDescription);
|
|
$descriptionInput.trigger("blur");
|
|
updatePartsList();
|
|
});
|
|
|
|
$("#partsList").on("click", "li", function (e) {
|
|
if ($(e.target).hasClass("add-to-mix-btn")) return;
|
|
selectedPartNumber = $(this).data("part-number");
|
|
$(this).addClass("active").siblings().removeClass("active");
|
|
});
|
|
|
|
// ===================
|
|
// MARKERS & DESCRIPTIONS
|
|
// ===================
|
|
const canvas = document.getElementById("photoCanvas");
|
|
const ctx = canvas.getContext("2d");
|
|
|
|
$("#markerContainer").on("click", function (e) {
|
|
if (selectedPartNumber === null) return;
|
|
|
|
const rect = canvas.getBoundingClientRect();
|
|
const clickX = e.clientX - rect.left;
|
|
const clickY = e.clientY - rect.top;
|
|
|
|
const x = clickX / photoData.scale;
|
|
const y = clickY / photoData.scale;
|
|
|
|
const currentPhoto = $("#samplePhoto").attr("src");
|
|
if (!photoMarkers[currentPhoto]) photoMarkers[currentPhoto] = [];
|
|
|
|
const existingMarker = photoMarkers[currentPhoto].find(
|
|
(m) => m.partNumber == selectedPartNumber,
|
|
);
|
|
if (existingMarker) {
|
|
existingMarker.x = x;
|
|
existingMarker.y = y;
|
|
} else {
|
|
photoMarkers[currentPhoto].push({
|
|
partNumber: selectedPartNumber,
|
|
x,
|
|
y,
|
|
});
|
|
}
|
|
|
|
updateMarkers();
|
|
if (hasDescriptions)
|
|
drawDescriptions(descriptionPosition.x, descriptionPosition.y);
|
|
|
|
selectedPartNumber = null;
|
|
$("#partsList li").removeClass("active");
|
|
});
|
|
|
|
function updateMarkers() {
|
|
const markerContainer = $("#markerContainer");
|
|
markerContainer.empty();
|
|
|
|
markerContainer.css({
|
|
width: `${photoData.displayWidth}px`,
|
|
height: `${photoData.displayHeight}px`,
|
|
});
|
|
|
|
const currentPhoto = $("#samplePhoto").attr("src");
|
|
const markers = photoMarkers[currentPhoto] || [];
|
|
|
|
markers.forEach((marker) => {
|
|
const scaledX = marker.x * photoData.scale;
|
|
const scaledY = marker.y * photoData.scale;
|
|
|
|
const $marker = $(
|
|
`<div class="draggable-marker">${marker.partNumber}</div>`,
|
|
).css({
|
|
left: scaledX - 8 + "px",
|
|
top: scaledY - 8 + "px",
|
|
});
|
|
markerContainer.append($marker);
|
|
makeDraggable($marker, marker);
|
|
});
|
|
}
|
|
|
|
function makeDraggable($element, item) {
|
|
let isDragging = false;
|
|
let startLeft = 0;
|
|
let startTop = 0;
|
|
let initialX = 0;
|
|
let initialY = 0;
|
|
|
|
$element.on("mousedown", function (e) {
|
|
e.preventDefault();
|
|
isDragging = true;
|
|
startLeft = parseFloat($element.css("left")) || 0;
|
|
startTop = parseFloat($element.css("top")) || 0;
|
|
initialX = e.clientX - startLeft;
|
|
initialY = e.clientY - startTop;
|
|
$element.css("z-index", 1001);
|
|
});
|
|
|
|
$(document).on("mousemove.dragMarker", function (e) {
|
|
if (!isDragging) return;
|
|
let currentX = e.clientX - initialX;
|
|
let currentY = e.clientY - initialY;
|
|
|
|
const maxX = photoData.displayWidth - $element.width();
|
|
const maxY = photoData.displayHeight - $element.height();
|
|
|
|
currentX = Math.max(0, Math.min(currentX, maxX));
|
|
currentY = Math.max(0, Math.min(currentY, maxY));
|
|
|
|
$element.css({ left: currentX + "px", top: currentY + "px" });
|
|
|
|
if (item && item.partNumber) {
|
|
item.x = (currentX + 8) / photoData.scale;
|
|
item.y = (currentY + 8) / photoData.scale;
|
|
} else {
|
|
descriptionPosition.x = (currentX + 5) / photoData.scale;
|
|
descriptionPosition.y = (currentY + 5) / photoData.scale;
|
|
}
|
|
});
|
|
|
|
$(document).on("mouseup.dragMarker", function () {
|
|
if (!isDragging) return;
|
|
isDragging = false;
|
|
$element.css("z-index", 1000);
|
|
$(document).off("mousemove.dragMarker mouseup.dragMarker");
|
|
});
|
|
}
|
|
|
|
function drawDescriptions(x, y) {
|
|
const partsList = [];
|
|
$("#partsTableBody tr").each(function () {
|
|
const partNumber = $(this).find(".part-number").val();
|
|
const partDescription = $(this).find(".part-description").val();
|
|
if (
|
|
partNumber &&
|
|
partDescription &&
|
|
!partDescription.startsWith("Mix")
|
|
) {
|
|
partsList.push(`${partNumber} ${partDescription}`);
|
|
}
|
|
});
|
|
|
|
const descriptionList = $("#descriptionList");
|
|
descriptionList.empty();
|
|
descriptionList.css({
|
|
display: "block",
|
|
top: y * photoData.scale + "px",
|
|
left: x * photoData.scale + "px",
|
|
});
|
|
partsList.forEach((part) =>
|
|
descriptionList.append(`<div>${part}</div>`),
|
|
);
|
|
|
|
updateMarkers();
|
|
}
|
|
|
|
function clearCanvasMarkers() {
|
|
const currentPhoto = $("#samplePhoto").attr("src");
|
|
photoMarkers[currentPhoto] = [];
|
|
hasDescriptions = false;
|
|
$("#descriptionList").css("display", "none");
|
|
$("#markerContainer").empty();
|
|
|
|
const canvas = document.getElementById("photoCanvas");
|
|
const ctx = canvas.getContext("2d");
|
|
|
|
canvas.width = photoData.naturalWidth;
|
|
canvas.height = photoData.naturalHeight;
|
|
canvas.style.width = `${photoData.displayWidth}px`;
|
|
canvas.style.height = `${photoData.displayHeight}px`;
|
|
|
|
const img = $("#samplePhoto");
|
|
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
|
if (img[0].naturalWidth) {
|
|
ctx.drawImage(img.get(0), 0, 0, canvas.width, canvas.height);
|
|
}
|
|
}
|
|
|
|
$("#addDescriptionsBtn").on("click", function () {
|
|
console.log("Aggiungi descrizioni cliccato");
|
|
hasDescriptions = true;
|
|
descriptionPosition = { x: 10, y: 10 };
|
|
drawDescriptions(descriptionPosition.x, descriptionPosition.y);
|
|
makeDraggable($("#descriptionList"));
|
|
});
|
|
|
|
$("#removeAnnotationsBtn").on("click", function () {
|
|
console.log("Rimuovi annotazioni cliccato");
|
|
clearCanvasMarkers();
|
|
});
|
|
|
|
// ===================
|
|
// REMOVE BACKGROUND (Remove.bg)
|
|
// ===================
|
|
$("#removeBackgroundBtn").on("click", function () {
|
|
console.log("Pulsante Rimuovi Sfondo cliccato");
|
|
|
|
if (
|
|
!REMOVE_BG_API_KEY ||
|
|
REMOVE_BG_API_KEY === "INSERISCI_LA_TUA_CHIAVE_API"
|
|
) {
|
|
alert(
|
|
"Chiave API di Remove.bg non configurata. Inserisci una chiave valida.",
|
|
);
|
|
console.error("Chiave API non valida");
|
|
return;
|
|
}
|
|
|
|
const currentPhoto = $("#samplePhoto")[0];
|
|
if (!currentPhoto.src) {
|
|
alert("Nessuna foto selezionata.");
|
|
console.error("Nessuna immagine in #samplePhoto");
|
|
return;
|
|
}
|
|
|
|
console.log("Immagine corrente:", currentPhoto.src);
|
|
|
|
// Salva marker e descrizioni
|
|
const currentPhotoKey = currentPhoto.src;
|
|
const markers = photoMarkers[currentPhotoKey] || [];
|
|
const descPos = { ...descriptionPosition };
|
|
const hasDesc = hasDescriptions;
|
|
|
|
// Mostra spinner
|
|
$("#removeBackgroundBtn")
|
|
.html('<i class="fas fa-spinner fa-spin"></i> Elaborazione...')
|
|
.prop("disabled", true);
|
|
|
|
// Controlla se l'immagine è un URL pubblico o un dataURL
|
|
const formData = new FormData();
|
|
if (currentPhoto.src.startsWith("data:")) {
|
|
// Converti dataURL in blob
|
|
console.log("Immagine è un dataURL, conversione in blob...");
|
|
fetch(currentPhoto.src)
|
|
.then((res) => res.blob())
|
|
.then((blob) => {
|
|
formData.append("image_file", blob, "image.png");
|
|
formData.append("size", "auto");
|
|
sendRemoveBgRequest(formData, markers, descPos, hasDesc);
|
|
})
|
|
.catch((err) => {
|
|
console.error("Errore conversione dataURL in blob:", err);
|
|
alert("Errore nella conversione dell'immagine.");
|
|
$("#removeBackgroundBtn")
|
|
.html("Rimuovi Sfondo")
|
|
.prop("disabled", false);
|
|
});
|
|
} else {
|
|
// Usa URL pubblico
|
|
console.log("Immagine è un URL, invio diretto...");
|
|
formData.append("image_url", currentPhoto.src);
|
|
formData.append("size", "auto");
|
|
sendRemoveBgRequest(formData, markers, descPos, hasDesc);
|
|
}
|
|
});
|
|
|
|
function sendRemoveBgRequest(formData, markers, descPos, hasDesc) {
|
|
console.log("Invio richiesta a Remove.bg...");
|
|
$.ajax({
|
|
url: "https://api.remove.bg/v1.0/removebg",
|
|
method: "POST",
|
|
headers: {
|
|
"X-Api-Key": REMOVE_BG_API_KEY,
|
|
},
|
|
data: formData,
|
|
processData: false,
|
|
contentType: false,
|
|
success: function (response) {
|
|
console.log("Risposta Remove.bg ricevuta:", response);
|
|
// Ripristina il pulsante
|
|
$("#removeBackgroundBtn")
|
|
.html("Rimuovi Sfondo")
|
|
.prop("disabled", false);
|
|
|
|
// Imposta l'immagine senza sfondo
|
|
const dataURL =
|
|
"data:image/png;base64," + response.data.result_b64;
|
|
$("#samplePhoto").attr("src", dataURL);
|
|
|
|
// Ripristina marker e descrizioni
|
|
photoMarkers[dataURL] = markers;
|
|
descriptionPosition = descPos;
|
|
hasDescriptions = hasDesc;
|
|
|
|
loadSinglePhoto(dataURL);
|
|
markUnsaved();
|
|
},
|
|
error: function (xhr) {
|
|
console.error(
|
|
"Errore API Remove.bg:",
|
|
xhr.status,
|
|
xhr.responseText,
|
|
);
|
|
alert(
|
|
"Errore nella rimozione dello sfondo: " +
|
|
(xhr.responseJSON?.errors?.[0]?.title ||
|
|
xhr.statusText),
|
|
);
|
|
$("#removeBackgroundBtn")
|
|
.html("Rimuovi Sfondo")
|
|
.prop("disabled", false);
|
|
},
|
|
});
|
|
}
|
|
|
|
let unsavedChanges = false;
|
|
|
|
// --- helper functions ---
|
|
function markUnsaved() {
|
|
if (!unsavedChanges) {
|
|
unsavedChanges = true;
|
|
$("#savePhotoBtn").addClass("unsaved").text("⚠️ Salva Modifiche");
|
|
console.log("Modifiche non salvate segnate");
|
|
}
|
|
}
|
|
|
|
function clearUnsaved() {
|
|
unsavedChanges = false;
|
|
$("#savePhotoBtn").removeClass("unsaved").text("Salva Foto con Nome");
|
|
console.log("Modifiche salvate, stato ripristinato");
|
|
}
|
|
|
|
// --- event listeners ---
|
|
$(document).on("input change", "#partsTableBody input", markUnsaved);
|
|
$(document).on("click", ".add-row, .add-mix-row, .remove-row", markUnsaved);
|
|
$(document).on("markerChanged descriptionChanged", markUnsaved);
|
|
|
|
// --- modal close protection ---
|
|
$("#partsModal").on("hide.bs.modal", function (e) {
|
|
if (unsavedChanges) {
|
|
if (!confirm("Hai modifiche non salvate. Vuoi davvero uscire?")) {
|
|
e.preventDefault();
|
|
}
|
|
}
|
|
});
|
|
|
|
// --- SAVE BUTTON (disabilitato per ora) ---
|
|
$("#savePhotoBtn").on("click", function () {
|
|
alert("Funzionalità di salvataggio non implementata per ora.");
|
|
console.log("Pulsante Salva Foto cliccato");
|
|
});
|
|
|
|
// ===================
|
|
// DEBUG HOVER LOGS
|
|
// ===================
|
|
$(document).on("mouseenter", "tr", function () {
|
|
console.log("Mouse entrato su riga");
|
|
});
|
|
|
|
$(document).on("mouseleave", "tr", function () {
|
|
console.log("Mouse uscito da riga");
|
|
});
|
|
});
|