
// 自动排序函数
function arrangeIcons(desktopIconView, availableRowCount, availableColumnCount) {
    if (!desktopIconView || typeof desktopIconView.count === "undefined") {
        console.error("无效的 desktopIconView 参数");
        return;
    }
    var allItems = [];
    for (var i = 0; i < desktopIconView.count; i++) {
        var item = desktopIconView.itemAt(i);
        if (item) {
            allItems.push({
                uri: item.uri,
                pos: item.pos
            });
        }
    }
    var sortedItems = sortItemsByGrid(allItems)

    for (var i = 0; i < desktopIconView.count; i++) {
        var item = desktopIconView.itemAt(i);
        if (item) {
            var index = sortedItems.findIndex(sortedItems => sortedItems.uri === item.uri);
             if (index !== -1) {
                 console.log("找到", item.uri, "，位置:", allItems[index].pos, "，索引:", index);
                 var newX = Math.floor(index/availableRowCount)
                 var newY = index%availableColumnCount
                 item.pos.x = newX;
                 item.pos.y = newY;
                 item.x = newX*desktopIconView.gridWidth
                 item.y = newY*desktopIconView.gridheight
                 console.log("update position", item.uri, item.pos);
             } else {
                 console.log("未找到", item.uri);
             }
        }
    }
}

function sortItemsByGrid(items) {
    // 按 y (行) 升序，再按 x (列) 升序
    items.sort(function(a, b) {
        if (a.pos.y !== b.pos.y) {
            return a.pos.y - b.pos.y; // 先按 y 排序
        } else {
            return a.pos.x - b.pos.x; // 同一行再按 x 排序
        }
    });
    return items;
}
//function arrangeIcons() {
//    var columns = Math.floor(desktopIconView.width / (80 + 10)) // 每列图标数
//    for (var i = 0; i < model.count; ++i) {
//        var column = i % columns
//        var row = Math.floor(i / columns)
//        model.setProperty(i, "x", column * (80 + 10))
//        model.setProperty(i, "y", row * (80 + 10))
//    }
//}
//function getIndexByUri(uri) {
//    for (var i = 0; i < desktopIconView.count; i++) {
//        if (desktopIconView.itemAt(i).uri === uri) return i;
//    }
//    return -1;
//}
