<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>牙體技術師國考模擬測驗系統</title>
<style>
:root {
--bg: #f4f6f9;
--card: #ffffff;
--primary: #0f4c81;
--primary-hover: #0a365c;
--accent: #198754;
--danger: #c62828;
--text: #1e293b;
--muted: #64748b;
--border: #cbd5e1;
--opt-bg: #f8fafc;
--opt-active: #e0f2fe;
}
* {
box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
}
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Noto Sans TC", sans-serif;
background: var(--bg);
color: var(--text);
line-height: 1.6;
min-height: 100vh;
}
.watermark-layer {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 9999;
opacity: 0.06;
display: none;
grid-template-columns: repeat(3, 1fr);
gap: 48px;
padding: 24px;
transform: rotate(-22deg) scale(1.2);
user-select: none;
}
.watermark-item {
text-align: center;
font-size: 16px;
font-weight: 700;
color: #0f172a;
white-space: nowrap;
}
.container {
max-width: 820px;
margin: 0 auto;
padding: 16px;
}
.card {
background: var(--card);
border: 1px solid var(--border);
border-radius: 14px;
padding: 20px;
margin-bottom: 16px;
box-shadow: 0 2px 8px rgba(15, 23, 42, 0.04);
}
h1 {
margin: 0 0 6px;
font-size: 22px;
color: var(--primary);
}
.subtitle {
margin: 0;
color: var(--muted);
font-size: 14px;
}
.row {
display: flex;
gap: 10px;
flex-wrap: wrap;
align-items: center;
}
label {
display: block;
font-weight: 600;
font-size: 14px;
margin-bottom: 6px;
}
input[type="text"],
select {
width: 100%;
padding: 12px 14px;
font-size: 16px;
border: 1px solid var(--border);
border-radius: 10px;
background: #fff;
color: var(--text);
}
button {
cursor: pointer;
border: none;
border-radius: 10px;
padding: 12px 18px;
font-size: 15px;
font-weight: 600;
transition: background 0.15s ease, opacity 0.15s ease;
}
button:disabled {
opacity: 0.55;
cursor: not-allowed;
}
.btn-primary {
background: var(--primary);
color: #fff;
}
.btn-primary:hover:not(:disabled) {
background: var(--primary-hover);
}
.btn-secondary {
background: #e2e8f0;
color: var(--text);
}
.btn-success {
background: var(--accent);
color: #fff;
}
.btn-danger {
background: var(--danger);
color: #fff;
}
.status-bar {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 8px;
font-size: 13px;
color: var(--muted);
margin-top: 10px;
}
.badge {
display: inline-block;
padding: 3px 10px;
border-radius: 999px;
font-size: 12px;
font-weight: 700;
background: #e0f2fe;
color: var(--primary);
}
.question-card {
margin-bottom: 18px;
}
.q-meta {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 13px;
color: var(--muted);
margin-bottom: 8px;
}
.q-text {
font-size: 17px;
font-weight: 600;
margin-bottom: 12px;
white-space: pre-wrap;
}
.q-img-wrap {
margin-bottom: 14px;
text-align: center;
background: #f8fafc;
border: 1px solid #e2e8f0;
border-radius: 10px;
padding: 10px;
}
.q-img-wrap img {
max-width: 100%;
max-height: 360px;
border-radius: 6px;
object-fit: contain;
}
.options {
display: flex;
flex-direction: column;
gap: 10px;
}
.opt-btn {
width: 100%;
text-align: left;
background: var(--opt-bg);
border: 1.5px solid var(--border);
color: var(--text);
padding: 13px 14px;
border-radius: 10px;
font-size: 15px;
line-height: 1.45;
}
.opt-btn.selected {
background: var(--opt-active);
border-color: var(--primary);
color: var(--primary);
}
.opt-btn.correct-ans {
background: #dcfce7;
border-color: #15803d;
color: #14532d;
}
.opt-btn.wrong-ans {
background: #fee2e2;
border-color: #b91c1c;
color: #7f1d1d;
}
.exp-box {
margin-top: 12px;
padding: 12px 14px;
border-radius: 10px;
background: #f8fafc;
border-left: 4px solid var(--primary);
font-size: 14px;
white-space: pre-wrap;
}
.error-msg {
color: var(--danger);
font-size: 14px;
font-weight: 600;
margin-top: 8px;
}
.score-box {
text-align: center;
padding: 16px;
border-radius: 12px;
background: #f0f9ff;
border: 1px solid #bae6fd;
margin-bottom: 16px;
}
.score-num {
font-size: 36px;
font-weight: 800;
color: var(--primary);
}
.hidden {
display: none !important;
}
.sticky-footer {
position: sticky;
bottom: 0;
background: rgba(255, 255, 255, 0.96);
backdrop-filter: blur(6px);
border-top: 1px solid var(--border);
padding: 12px 16px;
z-index: 20;
}
.sticky-inner {
max-width: 820px;
margin: 0 auto;
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
}
</style>
</head>
<body>
<div id="watermarkLayer" class="watermark-layer" aria-hidden="true"></div>
<div class="container">
<div class="card">
<h1>牙體技術師國考模擬測驗系統</h1>
<p class="subtitle">支援牙體技術學(一)~(四)分科與全科隨機抽題、裝置綁定驗證與交卷詳解</p>
<div id="authStatusBar" class="status-bar hidden">
<div>
<span class="badge" id="buyerBadge">已授權</span>
<span id="deviceInfo" style="margin-left: 6px;"></span>
</div>
<button class="btn-secondary" style="padding: 6px 12px; font-size: 13px;" onclick="logoutLicense()">更換序號</button>
</div>
</div>
<!-- 1. 序號啟用區 -->
<div id="activateSection" class="card">
<label for="licenseInput">輸入授權序號</label>
<div class="row">
<input id="licenseInput" type="text" placeholder="例如:TEST-2026-0001" autocomplete="off" style="flex: 1; min-width: 200px;" />
<button id="activateBtn" class="btn-primary" onclick="activateLicense()">驗證並啟用</button>
</div>
<div id="activateError" class="error-msg"></div>
</div>
<!-- 2. 抽題設定區 -->
<div id="drawSection" class="card hidden">
<div class="row" style="align-items: flex-end;">
<div style="flex: 1.5; min-width: 200px;">
<label for="subjectSelect">選擇考科</label>
<select id="subjectSelect">
<option value="ALL">全科綜合抽題(一~四)</option>
<option value="DT1">牙體技術學(一)</option>
<option value="DT2">牙體技術學(二)</option>
<option value="DT3">牙體技術學(三)</option>
<option value="DT4">牙體技術學(四)</option>
</select>
</div>
<div style="flex: 1; min-width: 140px;">
<label for="countSelect">抽題題數</label>
<select id="countSelect">
<option value="20">20 題</option>
<option value="50" selected>50 題</option>
<option value="80">80 題</option>
<option value="100">100 題</option>
</select>
</div>
<button id="drawBtn" class="btn-primary" onclick="startExam()">開始抽題</button>
</div>
<div id="wrongBankRow" class="row hidden" style="margin-top: 12px;">
<button class="btn-secondary" onclick="startWrongReview()">錯題重練(<span id="wrongCountLabel">0</span> 題)</button>
</div>
<div id="drawError" class="error-msg"></div>
</div>
<!-- 3. 作答/檢討區 -->
<div id="resultSummaryCard" class="card hidden">
<div class="score-box">
<div>本次測驗得分</div>
<div class="score-num" id="scoreValue">0 分</div>
<div id="scoreDetailText" style="color: var(--muted); font-size: 14px;"></div>
</div>
<div class="row" style="justify-content: center;">
<button class="btn-primary" onclick="resetToDraw()">再抽一份試卷</button>
</div>
</div>
<div id="examArea"></div>
</div>
<div id="examFooter" class="sticky-footer hidden">
<div class="sticky-inner">
<div id="progressText" style="font-size: 14px; font-weight: 600;">已作答 0 / 0 題</div>
<button id="submitBtn" class="btn-success" onclick="submitExam()">交卷並看詳解</button>
</div>
</div>
<script>
const API_BASE_URL = "https://dental-exam-api.dalitim5487.workers.dev";
const STORAGE_KEYS = {
TOKEN: "dt_exam_token_v1",
DEVICE_ID: "dt_exam_device_id_v1",
BUYER_TAG: "dt_exam_buyer_tag_v1",
ALLOWED_SUBJECTS: "dt_exam_subjects_v1",
WRONG_UIDS: "dt_exam_wrong_uids_v1"
};
const SUBJECT_NAMES = {
ALL: "全科綜合(一~四)",
DT1: "牙體技術學(一)",
DT2: "牙體技術學(二)",
DT3: "牙體技術學(三)",
DT4: "牙體技術學(四)"
};
let currentSessionId = null;
let currentQuestions = [];
let userAnswers = {};
let isGraded = false;
function getOrCreateDeviceId() {
let did = localStorage.getItem(STORAGE_KEYS.DEVICE_ID);
if (!did || did.length < 16) {
const rand = crypto.randomUUID ? crypto.randomUUID() : (Date.now() + "-" + Math.random().toString(36).slice(2));
did = "DEV-" + rand.replace(/[^a-zA-Z0-9-]/g, "");
localStorage.setItem(STORAGE_KEYS.DEVICE_ID, did);
}
return did;
}
function getWrongUids() {
try {
const arr = JSON.parse(localStorage.getItem(STORAGE_KEYS.WRONG_UIDS) || "[]");
return Array.isArray(arr) ? arr : [];
} catch {
return [];
}
}
function saveWrongUids(uids) {
localStorage.setItem(STORAGE_KEYS.WRONG_UIDS, JSON.stringify(Array.from(new Set(uids))));
updateWrongBankUI();
}
function updateWrongBankUI() {
const wrongList = getWrongUids();
const row = document.getElementById("wrongBankRow");
const label = document.getElementById("wrongCountLabel");
if (wrongList.length > 0) {
row.classList.remove("hidden");
label.textContent = wrongList.length;
} else {
row.classList.add("hidden");
}
}
function applyWatermark(tag) {
const layer = document.getElementById("watermarkLayer");
if (!tag) {
layer.style.display = "none";
return;
}
layer.innerHTML = "";
for (let i = 0; i < 18; i++) {
const div = document.createElement("div");
div.className = "watermark-item";
div.textContent = `授權編號 ${tag}`;
layer.appendChild(div);
}
layer.style.display = "grid";
}
function applyAllowedSubjects(subjects) {
const select = document.getElementById("subjectSelect");
const allowedSet = new Set(Array.isArray(subjects) && subjects.length ? subjects : ["DT1", "DT2", "DT3", "DT4"]);
Array.from(select.options).forEach((opt) => {
if (opt.value === "ALL") {
opt.disabled = allowedSet.size === 0;
} else {
opt.disabled = !allowedSet.has(opt.value);
}
});
if (select.selectedOptions[0]?.disabled) {
const firstEnabled = Array.from(select.options).find((o) => !o.disabled);
if (firstEnabled) select.value = firstEnabled.value;
}
}
function enterLoggedInState(tag, subjects) {
const did = getOrCreateDeviceId();
document.getElementById("activateSection").classList.add("hidden");
document.getElementById("drawSection").classList.remove("hidden");
document.getElementById("authStatusBar").classList.remove("hidden");
document.getElementById("buyerBadge").textContent = `序號標記:${tag}`;
document.getElementById("deviceInfo").textContent = `裝置碼:${did.slice(0, 12)}...`;
applyWatermark(tag);
applyAllowedSubjects(subjects);
updateWrongBankUI();
}
function logoutLicense() {
localStorage.removeItem(STORAGE_KEYS.TOKEN);
localStorage.removeItem(STORAGE_KEYS.BUYER_TAG);
localStorage.removeItem(STORAGE_KEYS.ALLOWED_SUBJECTS);
currentSessionId = null;
currentQuestions = [];
userAnswers = {};
isGraded = false;
applyWatermark("");
document.getElementById("authStatusBar").classList.add("hidden");
document.getElementById("drawSection").classList.add("hidden");
document.getElementById("resultSummaryCard").classList.add("hidden");
document.getElementById("examFooter").classList.add("hidden");
document.getElementById("examArea").innerHTML = "";
document.getElementById("activateSection").classList.remove("hidden");
}
async function activateLicense() {
const input = document.getElementById("licenseInput");
const errEl = document.getElementById("activateError");
const btn = document.getElementById("activateBtn");
errEl.textContent = "";
const licenseKey = input.value.trim().toUpperCase();
if (!licenseKey) {
errEl.textContent = "請先輸入授權序號。";
return;
}
btn.disabled = true;
btn.textContent = "驗證中...";
try {
const res = await fetch(`${API_BASE_URL}/api/activate`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
licenseKey,
deviceId: getOrCreateDeviceId()
})
});
const data = await res.json();
if (!res.ok || !data.ok) {
errEl.textContent = data.error || "序號驗證失敗";
return;
}
localStorage.setItem(STORAGE_KEYS.TOKEN, data.token);
localStorage.setItem(STORAGE_KEYS.BUYER_TAG, data.buyerTag || licenseKey.slice(-4));
localStorage.setItem(STORAGE_KEYS.ALLOWED_SUBJECTS, JSON.stringify(data.allowedSubjects || ["DT1", "DT2", "DT3", "DT4"]));
enterLoggedInState(
data.buyerTag || licenseKey.slice(-4),
data.allowedSubjects || ["DT1", "DT2", "DT3", "DT4"]
);
} catch (e) {
errEl.textContent = "無法連線至測驗伺服器,請檢查網路或網址設定。";
} finally {
btn.disabled = false;
btn.textContent = "驗證並啟用";
}
}
async function startExam(customUids = null) {
const token = localStorage.getItem(STORAGE_KEYS.TOKEN);
const errEl = document.getElementById("drawError");
const btn = document.getElementById("drawBtn");
errEl.textContent = "";
if (!token) {
logoutLicense();
return;
}
const subject = document.getElementById("subjectSelect").value;
const count = Number(document.getElementById("countSelect").value || 50);
btn.disabled = true;
btn.textContent = "抽題中...";
document.getElementById("resultSummaryCard").classList.add("hidden");
try {
const payload = customUids
? { subject: "ALL", count: customUids.length, uids: customUids }
: { subject, count };
const res = await fetch(`${API_BASE_URL}/api/draw`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`
},
body: JSON.stringify(payload)
});
const data = await res.json();
if (res.status === 401 || res.status === 403) {
errEl.textContent = data.error || "授權已失效,請重新驗證序號。";
logoutLicense();
return;
}
if (!res.ok || !data.ok) {
errEl.textContent = data.error || "抽題失敗";
return;
}
currentSessionId = data.sessionId;
currentQuestions = Array.isArray(data.questions) ? data.questions : [];
userAnswers = {};
isGraded = false;
renderQuestions();
updateProgress();
document.getElementById("examFooter").classList.remove("hidden");
document.getElementById("submitBtn").disabled = false;
document.getElementById("submitBtn").textContent = "交卷並看詳解";
window.scrollTo({ top: document.getElementById("examArea").offsetTop - 16, behavior: "smooth" });
} catch (e) {
errEl.textContent = "抽題請求失敗,請稍後再試。";
} finally {
btn.disabled = false;
btn.textContent = "開始抽題";
}
}
function startWrongReview() {
const wrongUids = getWrongUids();
if (!wrongUids.length) return;
startExam(wrongUids);
}
function renderQuestions() {
const area = document.getElementById("examArea");
area.innerHTML = "";
currentQuestions.forEach((item, idx) => {
const card = document.createElement("div");
card.className = "card question-card";
card.id = `q-card-${item.uid}`;
const subjLabel = SUBJECT_NAMES[item.subject] || item.subject || "";
const srcLabel = item.source_id ? `原題號 #${item.source_id}` : item.uid;
let imgHtml = "";
if (item.img) {
const imgPath = item.img.startsWith("images/") ? item.img : `images/${item.img}`;
imgHtml = `
<div class="q-img-wrap">
<img src="${escapeAttr(imgPath)}" alt="題目附圖 ${escapeAttr(item.uid)}" loading="lazy" />
</div>
`;
}
const opts = ["A", "B", "C", "D"]
.map((optKey) => {
const optText = item[optKey.toLowerCase()] || "";
return `
<button
type="button"
class="opt-btn"
id="opt-${item.uid}-${optKey}"
onclick="selectOption('${escapeAttr(item.uid)}', '${optKey}')"
>
<strong>(${optKey})</strong> ${escapeHtml(optText)}
</button>
`;
})
.join("");
card.innerHTML = `
<div class="q-meta">
<span><strong>第 ${idx + 1} 題</strong>|${escapeHtml(subjLabel)}</span>
<span>${escapeHtml(srcLabel)}</span>
</div>
<div class="q-text">${escapeHtml(item.q || "")}</div>
${imgHtml}
<div class="options">${opts}</div>
<div id="exp-${item.uid}" class="exp-box hidden"></div>
`;
area.appendChild(card);
});
}
function selectOption(uid, optKey) {
if (isGraded) return;
userAnswers[uid] = optKey;
["A", "B", "C", "D"].forEach((k) => {
const btn = document.getElementById(`opt-${uid}-${k}`);
if (btn) btn.classList.toggle("selected", k === optKey);
});
updateProgress();
}
function updateProgress() {
const answeredCount = Object.keys(userAnswers).length;
const total = currentQuestions.length;
document.getElementById("progressText").textContent = `已作答 ${answeredCount} / ${total} 題`;
}
async function submitExam() {
if (isGraded || !currentSessionId) return;
const token = localStorage.getItem(STORAGE_KEYS.TOKEN);
const submitBtn = document.getElementById("submitBtn");
submitBtn.disabled = true;
submitBtn.textContent = "批改中...";
try {
const res = await fetch(`${API_BASE_URL}/api/grade`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`
},
body: JSON.stringify({
sessionId: currentSessionId,
answers: userAnswers
})
});
const data = await res.json();
if (!res.ok || !data.ok) {
alert(data.error || "交卷批改失敗");
submitBtn.disabled = false;
submitBtn.textContent = "交卷並看詳解";
return;
}
isGraded = true;
document.getElementById("examFooter").classList.add("hidden");
const detailMap = new Map((data.details || []).map((d) => [String(d.uid), d]));
const prevWrong = new Set(getWrongUids());
currentQuestions.forEach((q) => {
const uid = String(q.uid);
const d = detailMap.get(uid);
if (!d) return;
["A", "B", "C", "D"].forEach((k) => {
const btn = document.getElementById(`opt-${uid}-${k}`);
if (!btn) return;
btn.classList.remove("selected");
if (k === d.correctAns) btn.classList.add("correct-ans");
if (d.userAns === k && !d.isCorrect) btn.classList.add("wrong-ans");
});
if (d.isCorrect) {
prevWrong.delete(uid);
} else {
prevWrong.add(uid);
}
const expBox = document.getElementById(`exp-${uid}`);
if (expBox) {
const statusText = d.isCorrect
? `答對(正確答案:${d.correctAns})`
: `答錯(你的作答:${d.userAns || "未作答"}|正確答案:${d.correctAns})`;
expBox.innerHTML = `<div><strong>${escapeHtml(statusText)}</strong></div><div style="margin-top:6px;">${escapeHtml(d.exp || "無詳解資料")}</div>`;
expBox.classList.remove("hidden");
}
});
saveWrongUids(Array.from(prevWrong));
document.getElementById("scoreValue").textContent = `${data.score} 分`;
document.getElementById("scoreDetailText").textContent = `答對 ${data.correctCount} / ${data.totalQuestions} 題`;
document.getElementById("resultSummaryCard").classList.remove("hidden");
window.scrollTo({ top: 0, behavior: "smooth" });
} catch (e) {
alert("交卷連線失敗,請稍後再試。");
submitBtn.disabled = false;
submitBtn.textContent = "交卷並看詳解";
}
}
function resetToDraw() {
currentSessionId = null;
currentQuestions = [];
userAnswers = {};
isGraded = false;
document.getElementById("resultSummaryCard").classList.add("hidden");
document.getElementById("examFooter").classList.add("hidden");
document.getElementById("examArea").innerHTML = "";
updateWrongBankUI();
}
function escapeHtml(str) {
return String(str)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function escapeAttr(str) {
return escapeHtml(str).replace(/`/g, "`");
}
(function init() {
getOrCreateDeviceId();
const savedToken = localStorage.getItem(STORAGE_KEYS.TOKEN);
if (savedToken) {
const tag = localStorage.getItem(STORAGE_KEYS.BUYER_TAG) || "已啟用";
let subjects = ["DT1", "DT2", "DT3", "DT4"];
try {
const parsed = JSON.parse(localStorage.getItem(STORAGE_KEYS.ALLOWED_SUBJECTS) || "null");
if (Array.isArray(parsed) && parsed.length) subjects = parsed;
} catch {}
enterLoggedInState(tag, subjects);
}
})();
</script>
</body>
</html>