// 裁切最大像素点
var inputFolder = "D:\\python\\code\\PsProduct\\PsProduct\\input";
var outputFolder = "D:\\python\\code\\PsProduct\\PsProduct\\output";

// 从参数文件读取配置
var paramFile = new File(Folder.userData + "/ps_params.json");
// 自定义JSON解析函数（替代标准JSON.parse）
function parseJSON(jsonString) {
    var obj = {};
    try {
        eval("obj = " + jsonString);
    } catch(e) {
        $.writeln("JSON解析错误: " + e.message);
    }
    return obj;
}

var params; // 在外部定义 params 变量

// 通过参数文件读取配置
if (paramFile.exists) {
    paramFile.open("r");
    var jsonString = paramFile.read();
    paramFile.close();
    paramFile.remove();

    // 使用自定义解析代替JSON.parse
    var params = parseJSON(jsonString);
    inputFolder = params.input || inputFolder;
    outputFolder = params.output || outputFolder;
}

// 主处理逻辑
processFolder(new Folder(inputFolder), new Folder(outputFolder));

function processFolder(inputDir, outputDir) {
    if (!outputDir.exists) outputDir.create();

    var files = inputDir.getFiles(/\.(psd|jpg|png|tiff?)$/i);
    for (var i = 0; i < files.length; i++) {
        processFile(files[i], outputDir);
    }
}

function processFile(file, outputDir) {
    try {
        var doc = app.open(file);

        // 自动解锁背景层
        if (doc.artLayers.length > 0 && doc.artLayers[0].isBackgroundLayer) {
            doc.artLayers[0].isBackgroundLayer = false;
        }

        // 透明裁剪逻辑
        var originalBounds = [0, 0, doc.width.as("px"), doc.height.as("px")];
        var newBounds = doc.trim(TrimType.TRANSPARENT, true, true, true, true);
        if (newBounds && !arraysEqual(originalBounds, newBounds)) {
            doc.crop([newBounds[0], newBounds[1], newBounds[2]+1, newBounds[3]+1]);
        }

        // 保存文件
        saveAs(doc, new File(outputDir + "/" + file.name));
        doc.close(SaveOptions.DONOTSAVECHANGES);
    } catch(e) { /* 静默处理错误 */ }
}

function saveAs(doc, targetFile) {
    var pngOpt = new PNGSaveOptions();
    pngOpt.interlaced = false;
    pngOpt.compression = 3;
    doc.saveAs(targetFile, pngOpt, true);
}

function arraysEqual(a, b) {
    for (var i = 0; i < a.length; i++) {
        if (Math.round(a[i]) != Math.round(b[i])) return false;
    }
    return true;
}