// 主函数
function main() {
    if (app.documents.length === 0) {
        alert("请先打开AI文件");
        return;
    }

    var doc = app.activeDocument;
    var csvFile = File.openDialog("选择兽牌导出.csv文件");

    if (!csvFile) {
        alert("未选择文件");
        return;
    }

    // 导出目录：CSV 同目录下的 pdf_export
    var exportFolder = new Folder(csvFile.parent.fsName + "/pdf_export");
    if (!exportFolder.exists) {
        exportFolder.create();
    }

    // 读取CSV文件
    var data = readCSV(csvFile);

    if (data.length === 0) {
        alert("CSV文件为空");
        return;
    }

    var exportedCount = 0;

    // 遍历每一行数据
    for (var i = 0; i < data.length; i++) {
        var row = data[i];
        if (!row || row.length < 4) {
            continue;
        }

        var id = row[0];
        var name = row[1];
        var path = row[2];
        var type = row[3];

        if (type !== "精英") {
            continue; // 只处理精英类型
        }

        // 处理ID格式
        var formattedId = formatId(id);

        // 创建一份副本，避免连续修改原始模板
        // var workDoc = doc.duplicate();
        // workDoc.name = "兽牌_" + id + "_" + name;

        // 填充id图层
        fillLayer(doc, "id", formattedId);

        // 填充name图层
        fillLayer(doc, "name", name);

        // 替换pic图层的图片，并嵌入
        if (path && path !== "") {
            var imageFile = resolveImageFile(csvFile, path);
            if (imageFile && imageFile.exists) {
                replacePicLayer(doc, "pic", imageFile);
            }
        }

        // 导出PDF
        var pdfFileName = createPdfFileName(id, name);
        var pdfFile = new File(exportFolder.fsName + "/" + pdfFileName);
        exportPdf(doc, pdfFile);

        // 关闭副本
        // workDoc.close(SaveOptions.DONOTSAVECHANGES);

        exportedCount++;
    }

    alert("已导出 " + exportedCount + " 个 PDF");
}

// 读取CSV文件
function readCSV(file) {
    var data = [];
    file.open("r");

    while (!file.eof) {
        var line = file.readln();
        if (line) {
            var cells = line.split(",");
            data.push(cells);
        }
    }

    file.close();
    return data;
}

// 格式化ID："1257" -> "00 / 00 / 12 / 57"
function formatId(id) {
    id = id.toString();

    // 补零至4位
    while (id.length < 4) {
        id = "0" + id;
    }

    // 分割为4段，每2位一段
    var part1 = id.substring(0, 2);
    var part2 = id.substring(2, 4);

    return "00 / 00 / " + part1 + " / " + part2;
}

// 填充文本图层
function fillLayer(doc, layerName, text) {
    for (var i = 0; i < doc.layers.length; i++) {
        if (doc.layers[i].name === layerName) {
            var layer = doc.layers[i];
            for (var j = 0; j < layer.pageItems.length; j++) {
                if (layer.pageItems[j].typename === "TextFrame") {
                    layer.pageItems[j].contents = text;
                    return;
                }
            }
        }
    }
}

// 解析图片路径，支持相对路径和绝对路径
function resolveImageFile(csvFile, pathValue) {
    var trimmedPath = pathValue.toString().trim();
    if (!trimmedPath) {
        return null;
    }

    var candidate = new File(trimmedPath);
    if (candidate.exists) {
        return candidate;
    }

    var relativeCandidate = new File(csvFile.parent.fsName + "/" + trimmedPath);
    if (relativeCandidate.exists) {
        return relativeCandidate;
    }

    return null;
}

// 替换图层中的图片，并嵌入
function replacePicLayer(doc, layerName, imageFile) {
    for (var i = 0; i < doc.layers.length; i++) {
        if (doc.layers[i].name === layerName) {
            var layer = doc.layers[i];
            for (var j = 0; j < layer.pageItems.length; j++) {
                var item = layer.pageItems[j];
                if (item.typename === "PlacedItem") {
                    item.file = imageFile;

                    try {
                        item.embed();
                    } catch (e) {
                        // 某些版本 Illustrator 对 embed() 的支持可能不同，忽略异常
                    }

                    return;
                }
            }
        }
    }
}

// 生成 PDF 文件名：id_name.pdf
function createPdfFileName(id, name) {
    var safeId = id.toString();
    var safeName = name.toString();

    // safeName = safeName.replace(/[\\/:*?"<>|]/g, "_");
    // safeName = safeName.replace(/\s+/g, "_");

    // if (!safeName) {
    //     safeName = "未命名";
    // }

    return safeId + "_" + safeName + ".pdf";
}

// 导出PDF，使用 PDF/X-4:2008 (Japan) 预设，并设置相关选项
function exportPdf(doc, pdfFile) {
    var pdfSaveOptions = new PDFSaveOptions();

    try {
        pdfSaveOptions.presetName = "[PDF/X-4:2008 (Japan)]";
    } catch (e) {}

    try {
        pdfSaveOptions.pdfPreset = "[PDF/X-4:2008 (Japan)]";
    } catch (e) {}

    try {
        pdfSaveOptions.compatibility = PDFCompatibility.PDFX4;
    } catch (e) {}

    // 常规设置：从顶层图层创建 Acrobat 图层
    try {
        pdfSaveOptions.acrobatLayers = true;
    } catch (e) {}

    // 尽量关闭下采样，避免降低像素
    try {
        pdfSaveOptions.downsampleImages = false;
    } catch (e) {}

    try {
        pdfSaveOptions.downsampleLinkedImages = false;
    } catch (e) {}

    doc.saveAs(pdfFile, pdfSaveOptions);
}

// 运行脚本
main();