<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>滑轨控制器</title>
    <style>
        body { font-family: sans-serif; max-width: 600px; margin: 20px auto; }
        .control-panel { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; }
        .control-group { border: 1px solid #ccc; padding: 10px; border-radius: 5px; }
        h3 { border-bottom: 2px solid #eee; padding-bottom: 5px; }
        button { font-size: 1.1em; padding: 10px; width: 100%; cursor: pointer; }
        input[type="text"] { width: calc(100% - 20px); padding: 5px; }
        .pos-display { font-size: 2.5em; font-weight: bold; color: #007bff; text-align: center; margin: 20px 0; }
        .pos-display span { font-size: 0.5em; color: #333; }
        .warn { background-color: #fff3cd; color: #856404; padding: 10px; border-radius: 5px; }
    </style>
</head>
<body>
    <h1>滑轨控制器</h1>

    <div class="pos-display">
        <span id="pos-display">0.00</span> <span>cm (工作区坐标)</span>
    </div>

    <div class="control-panel">
        <div class="control-group">
            <h3>1. 校准 (开机必点)</h3>
            <p class="warn"><b>注意：</b>点此前，请务必<b>手动将滑块推到最左侧 (物理0点)</b>！</p>
            <button id="btn-calibrate">开机校准 (移至1cm处)</button>
        </div>

        <div class="control-group">
            <h3>2. 归零</h3>
            <p>让滑块返回工作0点 (1cm处)。</p>
            <button id="btn-go-zero">工作归零 (返回0点)</button>
        </div>

        <div class="control-group">
            <h3>3. 速度设置</h3>
            <button id="btn-speed-slow">慢速</button>
            <button id="btn-speed-medium" style="margin-top:5px;">中速</button>
            <button id="btn-speed-fast" style="margin-top:5px;">快速</button>
            <hr>
            <input type="text" id="custom-speed" placeholder="自定义 (如 0.0008)">
            <button id="btn-speed-custom" style="margin-top:5px;">设置自定义</button>
        </div>

        <div class="control-group">
            <h3>4. 点动 (0.5cm)</h3>
            <p>在当前速度下，相对移动。</p>
            <div style="display:flex; gap: 10px;">
                <button id="btn-move-left">◀ 左移 0.5cm</button>
                <button id="btn-move-right">▶ 右移 0.5cm</button>
            </div>
        </div>

        <div class="control-group" style="grid-column: 1 / -1;">
            <h3>5. 绝对定位 (工作区 0-20cm)</h3>
            <input type="text" id="target-cm" placeholder="输入目标位置 (如 10.5)">
            <button id="btn-go-abs" style="margin-top:5px;">移动到指定位置</button>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const posDisplay = document.getElementById('pos-display');

            // --- 核心API调用函数 ---
            async function callApi(endpoint, method = 'POST', body = null) {
                try {
                    const options = {
                        method: method,
                        headers: { 'Content-Type': 'application/json' }
                    };
                    if (body) {
                        options.body = JSON.stringify(body);
                    }
                    
                    const response = await fetch(endpoint, options);
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    const data = await response.json();
                    updateDisplay(data);
                } catch (error) {
                    console.error('API call failed:', error);
                    alert('操作失败: ' + error.message);
                }
            }

            // --- 更新显示 ---
            function updateDisplay(data) {
                if (data && data.working_position_cm !== undefined) {
                    posDisplay.textContent = data.working_position_cm.toFixed(2);
                }
            }
            
            // --- 初始加载时获取一次状态 ---
            callApi('/status', 'GET');

            // --- 绑定按钮事件 ---
            
            // 1. 校准
            document.getElementById('btn-calibrate').addEventListener('click', () => {
                if (confirm('请确认：是否已手动将滑块推到最左侧物理0点？')) {
                    callApi('/calibrate');
                }
            });

            // 2. 归零
            document.getElementById('btn-go-zero').addEventListener('click', () => {
                callApi('/go_zero');
            });

            // 3. 速度
            document.getElementById('btn-speed-slow').addEventListener('click', () => callApi('/set_speed', 'POST', { speed: 'slow' }));
            document.getElementById('btn-speed-medium').addEventListener('click', () => callApi('/set_speed', 'POST', { speed: 'medium' }));
            document.getElementById('btn-speed-fast').addEventListener('click', () => callApi('/set_speed', 'POST', { speed: 'fast' }));
            document.getElementById('btn-speed-custom').addEventListener('click', () => {
                const speed = document.getElementById('custom-speed').value;
                if (speed) {
                    callApi('/set_speed', 'POST', { speed: speed });
                }
            });

            // 4. 点动
            document.getElementById('btn-move-left').addEventListener('click', () => {
                callApi('/move_relative', 'POST', { direction: 'left', cm: 0.5 });
            });
            document.getElementById('btn-move-right').addEventListener('click', () => {
                callApi('/move_relative', 'POST', { direction: 'right', cm: 0.5 });
            });

            // 5. 绝对定位
            document.getElementById('btn-go-abs').addEventListener('click', () => {
                const target = document.getElementById('target-cm').value;
                if (target !== '') {
                    callApi('/move_absolute', 'POST', { target_cm: target });
                }
            });
        });
    </script>
</body>
</html>
