import wixData from 'wix-data';
import wixLocation from 'wix-location';
import wixUsers from 'wix-users';
import {uploadFile} from 'wix-storage';
$w.onReady(function () {
// 获取当前产品ID
const productId = wixLocation.query.productId;
if (productId) {
loadProductImages(productId);
setupUploadButton(productId);
}
});
// 加载产品相关图片
function loadProductImages(productId) {
$w("#imageRepeater").data = []; // 清空重复器
wixData.query("ProductImages")
.eq("productId", productId)
.ascending("order")
.find()
.then(results => {
if (results.items.length > 0) {
$w("#imageRepeater").data = results.items;
$w("#imageRepeater").forEachItem(($item, itemData) => {
$item("#imageComponent").src = itemData.image;
$item("#captionText").text = itemData.caption;
});
} else {
$w("#noImagesMessage").show();
}
})
.catch(error => {
console.error("Error loading images:", error);
$w("#errorMessage").show();
});
}
// 设置上传按钮功能
function setupUploadButton(productId) {
// 检查用户是否已登录(只有管理员才能上传)
wixUsers.currentUser.getRoles()
.then(roles => {
const isAdmin = roles.some(role => role.name === "Admin");
if (isAdmin) {
$w("#uploadButton").show();
$w("#uploadButton").onClick(() => {
uploadNewImage(productId);
});
}
});
}
// 处理图片上传
async function uploadNewImage(productId) {
try {
// 打开文件选择对话框
const file = await uploadFile({
mediaType: "image",
multiple: false,
maxSize: 10 // MB
});
if (file) {
// 获取图片描述
const caption = await prompt("请输入图片描述:");
// 保存到数据库
const newImageData = {
productId: productId,
image: file.url,
caption: caption,
order: 0 // 默认排序
};
await wixData.insert("ProductImages", newImageData);
loadProductImages(productId); // 重新加载图片
$w("#successMessage").show().then(() => setTimeout(() => $w("#successMessage").hide(), 3000));
}
} catch (error) {
console.error("Upload error:", error);
$w("#uploadError").show();
}
}
// 辅助函数: 提示用户输入
function prompt(message) {
return new Promise((resolve) => {
$w("#promptDialog").show();
$w("#promptMessage").text = message;
$w("#promptConfirm").onClick(() => {
resolve($w("#promptInput").value);
$w("#promptDialog").hide();
});
$w("#promptCancel").onClick(() => {
resolve(null);
$w("#promptDialog").hide();
});
});
}
top of page
bottom of page