<!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 {
            margin: 0;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, #eff6ff, #f8fafc);
            font-family: Arial, sans-serif;
        }
        .card {
            width: 420px;
            padding: 28px;
            border-radius: 16px;
            background: #fff;
            box-shadow: 0 12px 40px rgba(0, 0, 0, 0.08);
        }
        h1 {
            margin-top: 0;
            margin-bottom: 12px;
            text-align: center;
        }
        .tips {
            color: #475467;
            text-align: center;
            margin-bottom: 20px;
        }
        .rule-tips {
            margin-top: -8px;
            margin-bottom: 16px;
            color: #667085;
            font-size: 13px;
            line-height: 1.6;
            text-align: center;
        }
        button {
            width: 100%;
            border: none;
            border-radius: 10px;
            background: #1677ff;
            color: #fff;
            padding: 12px;
            font-size: 15px;
            cursor: pointer;
        }
        .secondary {
            background: #4b5563;
        }
        .result {
            margin-top: 16px;
            padding: 16px;
            border-radius: 12px;
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            word-break: break-all;
            white-space: pre-wrap;
        }
        .error {
            color: #b42318;
        }
        .action-row {
            display: none;
            gap: 10px;
            margin-top: 16px;
        }
        .action-row.show {
            display: flex;
        }
        .action-row button {
            flex: 1;
        }
        .code-button {
            background: #dc2626;
        }
        .code-button.ready {
            background: #16a34a;
        }
        .field {
            margin-top: 14px;
            display: none;
        }
        .field.show {
            display: block;
        }
        .field label {
            display: block;
            margin-bottom: 6px;
            color: #475467;
            font-size: 13px;
        }
        .field textarea,
        .field input {
            width: 100%;
            box-sizing: border-box;
            border: 1px solid #d0d7de;
            border-radius: 10px;
            padding: 10px 12px;
            font-size: 14px;
        }
        .field textarea {
            min-height: 96px;
            resize: vertical;
            font-family: Consolas, monospace;
        }
        .toast {
            position: fixed;
            top: 18px;
            right: 18px;
            background: rgba(15, 23, 42, 0.92);
            color: #fff;
            padding: 10px 14px;
            border-radius: 10px;
            font-size: 13px;
            box-shadow: 0 10px 24px rgba(15, 23, 42, 0.2);
            opacity: 0;
            transform: translateY(-8px);
            pointer-events: none;
            transition: opacity 0.2s ease, transform 0.2s ease;
        }
        .toast.show {
            opacity: 1;
            transform: translateY(0);
        }
    </style>
</head>
<body>
<div class="card">
    <h1>获取卡密</h1>
    <div class="tips">当前类型：<span id="typeText">sitemap.xml</span></div>
    <div class="rule-tips">规则：卡密领取后会记录获取时间；如果 60 分钟内一直没有匹配到验证码，库存会自动恢复。</div>
    <div class="tips">名称为当前用户的通用耗材，不区分卡密分类；在任意卡密领取页都可以点击“获取名称”。</div>
    <div style="display: flex;flex-direction: row;margin: auto">
        <button style="margin: 10px 10px" id="claimButton" type="button">获取卡密</button>
        <button style="margin: 10px 10px"  id="claimNameButton" class="secondary" type="button">获取名称</button>
    </div>
    <div id="result" class="result">等待领取</div>
    <div id="actionRow" class="action-row">
        <button id="copyPhoneButton" class="secondary" type="button">复制手机号</button>
        <button id="copyCodeButton" class="code-button" type="button">复制验证码</button>

    </div>
    <div id="responseField" class="field">
        <label for="responseContent">接口返回内容</label>
        <textarea id="responseContent" readonly placeholder="等待轮询验证码接口"></textarea>
    </div>
    <div id="codeField" class="field">
        <label for="codeInput">匹配到的验证码</label>
        <input id="codeInput" type="text" readonly placeholder="暂未匹配到 6 位验证码">
    </div>
    <div id="nameField" class="field">
        <label for="nameInput">获取到的名称</label>
        <input id="nameInput" type="text" readonly placeholder="点击“获取名称”后显示结果">
    </div>
</div>
<div id="toast" class="toast"></div>
<script>
    const typeCode = "sitemap.xml";
    const resultBox = document.getElementById('result');
    const claimButton = document.getElementById('claimButton');
    const actionRow = document.getElementById('actionRow');
    const copyPhoneButton = document.getElementById('copyPhoneButton');
    const copyCodeButton = document.getElementById('copyCodeButton');
    const claimNameButton = document.getElementById('claimNameButton');
    const responseField = document.getElementById('responseField');
    const responseContent = document.getElementById('responseContent');
    const codeField = document.getElementById('codeField');
    const codeInput = document.getElementById('codeInput');
    const nameField = document.getElementById('nameField');
    const nameInput = document.getElementById('nameInput');
    const toast = document.getElementById('toast');
    let currentClaimData = '';
    let currentClaimUuid = '';
    let pollTimer = null;
    let polling = false;
    let claimingName = false;
    let toastTimer = null;

    if (!typeCode) {
        claimButton.disabled = true;
        resultBox.classList.add('error');
        resultBox.textContent = '缺少类型参数，请通过 /061601 这类路径访问页面';
    }

    copyPhoneButton.addEventListener('click', async () => {
        const segments = splitClaimData();
        if (!segments) {
            return;
        }
        await copyText(segments[0], '手机号已复制');
    });

    copyCodeButton.addEventListener('click', async () => {
        if (!codeInput.value) {
            resultBox.classList.add('error');
            resultBox.textContent = '暂未匹配到 6 位验证码，请等待接口轮询';
            return;
        }
        await copyText(codeInput.value, '验证码已复制');
    });

    claimNameButton.addEventListener('click', async () => {
        if (nameInput.value) {
            await copyText(nameInput.value, '名称已复制');
            return;
        }
        if (claimingName) {
            showToast('名称获取中，请稍候');
            return;
        }
        claimingName = true;
        try {
            const response = await fetch('/api/cards/claim-name', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ typeCode })
            });
            const result = await response.json();
            if (!response.ok || !result.success) {
                throw new Error(result.message || '获取名称失败');
            }
            nameField.classList.add('show');
            nameInput.value = result.data.name || '';
            updateClaimNameButton();
            await copyText(nameInput.value, '名称获取成功，已自动复制');
        } catch (error) {
            showToast(error.message);
        } finally {
            claimingName = false;
        }
    });

    claimButton.addEventListener('click', async () => {
        stopPolling();
        resultBox.classList.remove('error');
        claimButton.disabled = true;
        actionRow.classList.remove('show');
        responseField.classList.remove('show');
        codeField.classList.remove('show');
        nameField.classList.remove('show');
        responseContent.value = '';
        codeInput.value = '';
        nameInput.value = '';
        currentClaimUuid = '';
        updateClaimNameButton();
        copyCodeButton.classList.remove('ready');
        try {
            const response = await fetch('/api/cards/claim', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ typeCode })
            });
            const result = await response.json();
            if (!response.ok || !result.success) {
                throw new Error(result.message || '领取失败');
            }
            currentClaimData = `${result.data.cardNo}----${result.data.cardUrl}`;
            currentClaimUuid = result.data.claimUuid || '';
            actionRow.classList.add('show');
            responseField.classList.add('show');
            codeField.classList.add('show');
            resultBox.textContent = `领取成功\n手机号：${result.data.cardNo}\n验证码接口：${result.data.cardUrl}\n获取时间：${formatDateTime(result.data.claimedAt)}`;
            startPolling();
        } catch (error) {
            resultBox.classList.add('error');
            resultBox.textContent = error.message;
        } finally {
            claimButton.disabled = false;
        }
    });

    function splitClaimData() {
        const segments = currentClaimData.split('----');
        if (segments.length !== 2) {
            resultBox.classList.add('error');
            resultBox.textContent = '领取结果格式不正确，无法拆分手机号和验证码接口';
            return null;
        }
        return [segments[0].trim(), segments[1].trim()];
    }

    function startPolling() {
        void pollVerificationCode();
        pollTimer = window.setInterval(() => {
            void pollVerificationCode();
        }, 5000);
    }

    function stopPolling() {
        if (pollTimer) {
            window.clearInterval(pollTimer);
            pollTimer = null;
        }
        polling = false;
    }

    async function pollVerificationCode() {
        if (polling) {
            return;
        }
        const segments = splitClaimData();
        if (!segments) {
            stopPolling();
            return;
        }
        polling = true;
        try {
            const response = await fetch('/api/cards/verification-code', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ url: segments[1], claimUuid: currentClaimUuid })
            });
            const result = await response.json();
            if (!response.ok || !result.success) {
                throw new Error(result.message || '验证码接口请求失败');
            }
            responseContent.value = result.data.rawContent || '';
            if (result.data.code) {
                codeInput.value = result.data.code;
                copyCodeButton.classList.add('ready');
            } else {
                codeInput.value = '';
                copyCodeButton.classList.remove('ready');
            }
        } catch (error) {
            responseContent.value = error.message;
        } finally {
            polling = false;
        }
    }

    async function copyText(text, successMessage) {
        try {
            await navigator.clipboard.writeText(text);
            showToast(successMessage);
        } catch (error) {
            showToast('复制失败，请检查浏览器复制权限');
        }
    }

    function updateClaimNameButton() {
        claimNameButton.textContent = nameInput.value ? '复制名称' : '获取名称';
    }

    function formatDateTime(value) {
        if (!value) {
            return '';
        }
        return String(value).replace('T', ' ');
    }

    function showToast(message) {
        toast.textContent = message;
        toast.classList.add('show');
        if (toastTimer) {
            window.clearTimeout(toastTimer);
        }
        toastTimer = window.setTimeout(() => {
            toast.classList.remove('show');
        }, 1800);
    }

    updateClaimNameButton();
</script>
</body>
</html>
