// ============================================================
// 合肥轨道交通1号线 - 列车LCD脚本 (line1.js)
// 基于参考代码架构重写
// 适配：MTR 3.2.2+ / NTE 0.5.2+
// ============================================================

// --- 导入 Java 绘图类 ---
importPackage(java.awt);
importPackage(java.awt.geom);

// --- 加载内置辅助库 ---
include(Resources.id("mtrsteamloco:scripts/display_helper.js"));

// --- 辅助函数：计算屏幕顶点位置 (来自参考代码) ---
function getCubeVertices(p1, p2, center, rx, ry, rz) {
    const rxRad = rx * Math.PI / 180;
    const ryRad = ry * Math.PI / 180;
    const rzRad = rz * Math.PI / 180;
  
    let c = new Vector3f(center[0], center[1], center[2]);
  
    if (p1[1] == p2[1]) {
        let v1 = new Vector3f(p1[0], p1[1], p1[2]);
        let v2 = new Vector3f(p2[0], p1[1], p1[2]);
        let v3 = new Vector3f(p2[0], p2[1], p2[2]);
        let v4 = new Vector3f(p1[0], p2[1], p2[2]);
    
        v1.sub(c);
        v1.rotX(rxRad);
        v1.rotY(ryRad);
        v1.rotZ(rzRad);
        v1.add(c);
    
        v2.sub(c);
        v2.rotX(rxRad);
        v2.rotY(ryRad);
        v2.rotZ(rzRad);
        v2.add(c);
    
        v3.sub(c);
        v3.rotX(rxRad);
        v3.rotY(ryRad);
        v3.rotZ(rzRad);
        v3.add(c);
    
        v4.sub(c);
        v4.rotX(rxRad);
        v4.rotY(ryRad);
        v4.rotZ(rzRad);
        v4.add(c);
    
        return [
            [v1.x(), v1.y(), v1.z()],
            [v2.x(), v2.y(), v2.z()],
            [v3.x(), v3.y(), v3.z()],
            [v4.x(), v4.y(), v4.z()]
        ];
    }
    else if (p1[0] == p2[0]) {
        let v1 = new Vector3f(p1[0], p1[1], p1[2]);
        let v2 = new Vector3f(p1[0], p2[1], p1[2]);
        let v3 = new Vector3f(p2[0], p2[1], p2[2]);
        let v4 = new Vector3f(p2[0], p1[1], p2[2]);
    
        v1.sub(c);
        v1.rotX(rxRad);
        v1.rotY(ryRad);
        v1.rotZ(rzRad);
        v1.add(c);
    
        v2.sub(c);
        v2.rotX(rxRad);
        v2.rotY(ryRad);
        v2.rotZ(rzRad);
        v2.add(c);
    
        v3.sub(c);
        v3.rotX(rxRad);
        v3.rotY(ryRad);
        v3.rotZ(rzRad);
        v3.add(c);
    
        v4.sub(c);
        v4.rotX(rxRad);
        v4.rotY(ryRad);
        v4.rotZ(rzRad);
        v4.add(c);
    
        return [
            [v1.x(), v1.y(), v1.z()],
            [v2.x(), v2.y(), v2.z()],
            [v3.x(), v3.y(), v3.z()],
            [v4.x(), v4.y(), v4.z()]
        ];
    }
    else {
        throw "指定对角顶点不与地面垂直或平行：顶点一 [" + p1 + "]，顶点二 [" + p2 + "]。";
    }
}

// --- 屏幕配置 (使用 getCubeVertices 计算位置) ---
// 注意：以下坐标需要根据您的实际模型调整！
// p1, p2 是LCD屏幕的两个对角顶点，center 是旋转中心
const leftPos = getCubeVertices(
    [-0.589, 1.871, 0.537],  // p1
    [-0.777, 1.871, -0.522], // p2
    [-0.963, 1.795, 0],      // center
    0, 0, 50                 // rx, ry, rz (旋转角度)
);

let slotCfg = {
    "version": 1,
    "texSize": [512, 320],
    "slots": [
        {
            "name": "lcd_screen",
            "texArea": [0, 0, 512, 320],
            "pos": [leftPos],
            "offsets": [[0, 0, 0]]
        }
    ]
};

var dhBase = new DisplayHelper(slotCfg);

// --- 颜色常量 ---
const COLOR_LINE = Color.decode("#E61E25");
const COLOR_WHITE = Color.WHITE;
const COLOR_BLACK = Color.BLACK;
const COLOR_GRAY_170 = Color.decode("#AAAAAA");
const COLOR_GRAY_204 = Color.decode("#CCCCCC");
const COLOR_GRAY_136 = Color.decode("#888888");
const COLOR_GREEN = Color.decode("#00CC88");
const COLOR_CYAN = Color.decode("#00DDFF");
const COLOR_GOLD = Color.decode("#FFD700");
const COLOR_DOOR_OPEN = Color.decode("#00FF88");
const COLOR_DOOR_OPPOSITE = Color.decode("#FF8844");

// --- 字体常量 ---
const FONT_YAHEI = Resources.getSystemFont("Microsoft YaHei");
const FONT_ARIAL = Resources.getSystemFont("Arial");

// --- 换乘站数据 ---
var transferMap = {
    "合肥火车站": "可换乘 3号线",
    "大东门": "可换乘 2号线",
    "包公园": "可换乘 4号线",
    "合肥南站": "可换乘 4号线、5号线",
    "云谷路": "可换乘 5号线"
};

// --- NTE 核心函数 ---

function create(ctx, state, train) {
    state.leftPartUseCjkTracker = new CycleTracker([true, 5, false, 5]);
    state.dh = dhBase.create();
    state.currentStation = "待发车";
    state.nextStation = "--";
    state.destination = "--";
    state.doorSide = "--";
    state.isArrived = false;
    state.transferInfo = null;
    ctx.setDebugInfo("LCD", "create 完成");
}

function dispose(ctx, state, train) {
    state.dh.close();
    ctx.setDebugInfo("LCD", "已卸载");
}

function render(ctx, state, train) {
    // 绘制模型到所有车厢 (关键！)
    for (let i = 0; i < train.trainCars(); i++) {
        ctx.drawCarModel(state.dh.model, i, null);
    }

    state.leftPartUseCjkTracker.tick();

    if (train.shouldRender() && train.shouldRenderDetail()) {
        // 更新列车数据
        updateTrainData(state, train);
        updateTransferInfo(state);

        // 获取画笔并绘制
        let g = state.dh.graphicsFor("lcd_screen");
        drawLCD(g, state);

        // 上传纹理
        state.dh.upload();
    }

    // 调试信息
    ctx.setDebugInfo("当前站", state.currentStation);
    ctx.setDebugInfo("下一站", state.nextStation);
    ctx.setDebugInfo("终点站", state.destination);
    ctx.setDebugInfo("开门侧", state.doorSide);
    ctx.setDebugInfo("到站", state.isArrived ? "是" : "否");
    if (state.transferInfo) {
        ctx.setDebugInfo("换乘", state.transferInfo);
    }
}

// --- 数据更新函数 ---

function updateTrainData(state, train) {
    if (!train.isOnRoute()) {
        state.currentStation = "待发车";
        state.nextStation = "--";
        state.destination = "--";
        state.doorSide = "--";
        state.isArrived = false;
        return;
    }

    var allPlatforms = train.getAllPlatforms();
    var nextIndex = train.getAllPlatformsNextIndex();

    if (nextIndex < 0 || nextIndex > allPlatforms.length) {
        if (nextIndex === allPlatforms.length) {
            state.currentStation = "终点站";
            state.destination = "已到达";
            state.doorSide = "全侧开门";
            state.isArrived = true;
        }
        return;
    }

    var isAtStation = (train.doorValue() > 0.1 || train.speed() < 0.005);
    state.isArrived = isAtStation;

    if (nextIndex < allPlatforms.length) {
        var currentPlatform = allPlatforms[nextIndex];
        if (currentPlatform) {
            state.currentStation = formatName(currentPlatform.name);
        }
    }

    var nextIdx = nextIndex + 1;
    if (nextIdx < allPlatforms.length) {
        var nextPlatform = allPlatforms[nextIdx];
        if (nextPlatform) {
            state.nextStation = formatName(nextPlatform.name);
        }
    } else {
        state.nextStation = "终点站";
    }

    if (allPlatforms.length > 0) {
        var lastPlatform = allPlatforms[allPlatforms.length - 1];
        state.destination = formatName(lastPlatform.name);
    }

    var leftOpen = train.doorLeftOpen[0] || false;
    var rightOpen = train.doorRightOpen[0] || false;

    if (isAtStation) {
        if (leftOpen && !rightOpen) state.doorSide = "本侧开门";
        else if (rightOpen && !leftOpen) state.doorSide = "对侧开门";
        else if (leftOpen && rightOpen) state.doorSide = "两侧开门";
        else state.doorSide = "停站中";
    } else {
        state.doorSide = "行驶中";
    }
}

function updateTransferInfo(state) {
    var name = state.nextStation;
    if (!name || name === "--" || name === "终点站") {
        state.transferInfo = null;
        return;
    }
    state.transferInfo = transferMap[name] || null;
}

function formatName(name) {
    if (!name) return "未知车站";
    if (name.includes("|")) {
        return name.split("|")[0].trim();
    }
    return name.trim();
}

// --- 绘图函数 ---

function drawLCD(g, state) {
    var w = 512, h = 320;

    // 清空
    g.setColor(COLOR_BLACK);
    g.fillRect(0, 0, w, h);

    // 顶部色带
    g.setColor(COLOR_LINE);
    g.fillRect(0, 0, w, 24);

    var fm = g.getFontMetrics();

    // LOGO
    g.setFont(FONT_YAHEI.deriveFont(0, 16));
    g.setColor(COLOR_WHITE);
    g.drawString("合肥轨道", 16, 40);

    g.setFont(FONT_ARIAL.deriveFont(0, 12));
    g.setColor(COLOR_GRAY_170);
    g.drawString("HEFEI METRO", 16, 58);

    // 线路名
    g.setFont(FONT_YAHEI.deriveFont(0, 14));
    g.setColor(COLOR_WHITE);
    var lineName = "合肥轨道交通1号线";
    var lineNameEn = "Hefei Metro Line 1";
    var nameW = fm.stringWidth(lineName);
    g.drawString(lineName, w - 16 - nameW, 40);

    g.setFont(FONT_ARIAL.deriveFont(0, 11));
    g.setColor(COLOR_GRAY_170);
    var nameEnW = fm.stringWidth(lineNameEn);
    g.drawString(lineNameEn, w - 16 - nameEnW, 56);

    // 根据状态绘制
    if (state.isArrived) {
        drawArrived(g, w, h, state, fm);
    } else if (state.doorSide === "行驶中") {
        drawRunning(g, w, h, state, fm);
    } else if (state.currentStation === "待发车") {
        drawIdle(g, w, h, state, fm);
    } else {
        drawDeparting(g, w, h, state, fm);
    }

    drawFooter(g, w, h, fm);
}

function centerText(g, text, centerX, centerY, fm, font, color) {
    if (!text) return;
    g.setFont(font);
    g.setColor(color);
    var tw = fm.stringWidth(text);
    g.drawString(text, (centerX - tw) / 2, centerY);
}

function drawDeparting(g, w, h, state, fm) {
    centerText(g, "开往：" + state.destination, w, 120, fm, FONT_YAHEI.deriveFont(0, 36), COLOR_WHITE);
    centerText(g, "DESTINATION: " + state.destination.toUpperCase(), w, 152, fm, FONT_ARIAL.deriveFont(0, 18), COLOR_GRAY_204);
    centerText(g, "● " + state.currentStation, w, 200, fm, FONT_YAHEI.deriveFont(0, 28), COLOR_GREEN);
    centerText(g, "当前站", w, 228, fm, FONT_YAHEI.deriveFont(0, 16), COLOR_GRAY_170);
    centerText(g, "准备发车", w, 270, fm, FONT_YAHEI.deriveFont(0, 20), COLOR_GOLD);
}

function drawRunning(g, w, h, state, fm) {
    centerText(g, "下一站", w, 100, fm, FONT_YAHEI.deriveFont(0, 40), COLOR_WHITE);
    centerText(g, state.nextStation, w, 160, fm, FONT_YAHEI.deriveFont(0, 48), COLOR_CYAN);
    centerText(g, "NEXT STATION: " + state.nextStation.toUpperCase(), w, 196, fm, FONT_ARIAL.deriveFont(0, 20), COLOR_GRAY_170);

    if (state.transferInfo) {
        centerText(g, "★ " + state.transferInfo, w, 235, fm, FONT_YAHEI.deriveFont(0, 18), COLOR_GOLD);
    }

    var info = "当前：" + state.currentStation + " | 开往 " + state.destination;
    centerText(g, info, w, 275, fm, FONT_YAHEI.deriveFont(0, 16), COLOR_GRAY_136);
}

function drawArrived(g, w, h, state, fm) {
    centerText(g, state.currentStation, w, 115, fm, FONT_YAHEI.deriveFont(0, 52), COLOR_WHITE);
    centerText(g, "ARRIVED", w, 148, fm, FONT_ARIAL.deriveFont(0, 20), COLOR_GRAY_204);

    var isOpen = (state.doorSide === "本侧开门" || state.doorSide === "两侧开门");
    var isOpp = (state.doorSide === "对侧开门");
    var doorColor = isOpen ? COLOR_DOOR_OPEN : (isOpp ? COLOR_DOOR_OPPOSITE : COLOR_GRAY_136);
    centerText(g, state.doorSide, w, 195, fm, FONT_YAHEI.deriveFont(0, 26), doorColor);

    var doorEn = isOpen ? "DOORS OPEN AT THIS SIDE" : (isOpp ? "DOORS OPEN AT OPPOSITE" : "");
    if (doorEn) {
        centerText(g, doorEn, w, 222, fm, FONT_ARIAL.deriveFont(0, 14), COLOR_GRAY_170);
    }

    if (state.transferInfo) {
        centerText(g, "★ " + state.transferInfo, w, 260, fm, FONT_YAHEI.deriveFont(0, 18), COLOR_GOLD);
    }

    var bottom = "下一站 " + state.nextStation + " | 开往 " + state.destination;
    centerText(g, bottom, w, 288, fm, FONT_YAHEI.deriveFont(0, 14), COLOR_GRAY_136);
}

function drawIdle(g, w, h, state, fm) {
    centerText(g, "欢迎乘坐", w, 130, fm, FONT_YAHEI.deriveFont(0, 32), COLOR_GRAY_204);
    centerText(g, "合肥轨道交通1号线", w, 185, fm, FONT_YAHEI.deriveFont(0, 38), COLOR_WHITE);
    centerText(g, "HEFEI METRO LINE 1", w, 220, fm, FONT_ARIAL.deriveFont(0, 18), COLOR_GRAY_170);
}

function drawFooter(g, w, h, fm) {
    var y = h - 42;
    var values = ["富强", "民主", "文明", "和谐", "自由", "平等", "公正", "法治", "爱国", "敬业", "诚信", "友善"];

    var cw = [];
    var total = 0;
    for (var i = 0; i < values.length; i++) {
        cw.push(fm.stringWidth(values[i]));
        total += cw[i];
    }
    var spacing = (w - total) / (values.length + 1);
    var x = spacing;

    for (var i = 0; i < values.length; i++) {
        if (i < 4) {
            g.setColor(COLOR_GOLD);
            g.setFont(FONT_YAHEI.deriveFont(0, 14));
        } else {
            g.setColor(COLOR_GRAY_204);
            g.setFont(FONT_YAHEI.deriveFont(0, 14));
        }
        g.drawString(values[i], x, y);
        x += cw[i] + spacing;
    }
}