import { SHOP, CATEGORIES, DISHES, PROMOTIONS } from './menu.js' import { money, clock, getTable, setTable, readCart, writeCart, addToCart, changeQty, clearCart, totals, priceOf, submitOrder, updateOrder, orderById, readOrders, watch, STATUS, } from './store.js' const $ = (id) => document.getElementById(id) const esc = (text) => String(text ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])) let table = '' let currentDish = null let draft = { spec: {}, extras: [], qty: 1 } let activeOrderId = null let toastTimer = null // ---------- 基础 UI ---------- function toast(text) { const el = $('toast') el.textContent = text el.hidden = false clearTimeout(toastTimer) toastTimer = setTimeout(() => { el.hidden = true }, 1800) } function openSheet(id) { $(id).hidden = false } function closeSheet(id) { $(id).hidden = true } document.addEventListener('click', (event) => { const close = event.target.closest('[data-close]') if (close) closeSheet(close.dataset.close) }) // ---------- 顶部信息 ---------- function paintShop() { $('shopName').textContent = SHOP.name $('slogan').textContent = SHOP.slogan $('notice').textContent = SHOP.notice $('tableLabel').textContent = table ? `${table} 桌` : '选桌号' } function paintCats() { $('cats').innerHTML = CATEGORIES.map((cat) => ``).join('') } // ---------- 菜单 ---------- function paintMenu() { $('menu').innerHTML = CATEGORIES.map((cat) => { const dishes = DISHES.filter((dish) => dish.cat === cat.id) if (dishes.length === 0) return '' return `
${cat.icon} ${esc(cat.name)} ${dishes.length} 道
${dishes.map(dishCard).join('')}
` }).join('') } function dishCard(dish) { const tag = dish.tags[0] ? `${esc(dish.tags[0])}` : '' const extras = dish.extras?.length ? '· 可加料' : '' return `
${dish.emoji}
${esc(dish.name)} ${tag}

${esc(dish.desc)}

${money(dish.price)}
${dish.hot ? '🔥 热门' : esc(dish.tags[1] ?? '')} ${extras}
` } $('menu').addEventListener('click', (event) => { const card = event.target.closest('[data-dish]') if (!card) return const dish = DISHES.find((d) => d.id === card.dataset.dish) if (dish) openDish(dish) }) $('cats').addEventListener('click', (event) => { const button = event.target.closest('[data-cat]') if (!button) return document.querySelectorAll('.cat').forEach((el) => el.classList.toggle('on', el === button)) document.getElementById(`sec-${button.dataset.cat}`)?.scrollIntoView({ behavior: 'smooth', block: 'start' }) }) // ---------- 菜品详情 ---------- function openDish(dish) { currentDish = dish draft = { spec: {}, extras: [], qty: 1 } for (const group of dish.specs ?? []) draft.spec[group.name] = group.options[0] $('dishEmoji').textContent = dish.emoji $('dishName').textContent = dish.name $('dishDesc').textContent = dish.desc $('dishTags').innerHTML = dish.tags.map((tag) => `${esc(tag)}`).join('') $('dishNote').value = '' $('dishQty').textContent = '1' const groups = (dish.specs ?? []).map((group) => `

${esc(group.name)}

${group.options.map((option, index) => { const delta = Array.isArray(group.price) ? group.price[index] ?? 0 : 0 return `` }).join('')}
`).join('') const extras = dish.extras?.length ? `

加料(可多选)

${dish.extras.map((extra) => ``).join('')}
` : '' $('specArea').innerHTML = groups + extras paintDishFoot() openSheet('dishSheet') } function paintDishFoot() { const cents = priceOf(currentDish, draft.spec, draft.extras) * draft.qty $('dishQty').textContent = String(draft.qty) $('addToCart').textContent = `加入购物车 · ${money(cents)}` } $('specArea').addEventListener('click', (event) => { const option = event.target.closest('[data-opt]') if (option) { const group = option.closest('[data-group]').dataset.group draft.spec[group] = option.dataset.opt option.closest('.opts').querySelectorAll('.opt').forEach((el) => el.classList.toggle('on', el === option)) paintDishFoot() return } const extra = event.target.closest('[data-extra]') if (extra) { const name = extra.dataset.extra const index = draft.extras.indexOf(name) if (index >= 0) draft.extras.splice(index, 1) else draft.extras.push(name) extra.classList.toggle('on', index < 0) paintDishFoot() } }) document.querySelectorAll('[data-qty]').forEach((button) => { button.addEventListener('click', () => { draft.qty = Math.max(1, draft.qty + Number(button.dataset.qty)) paintDishFoot() }) }) $('addToCart').addEventListener('click', () => { addToCart(currentDish, { ...draft, note: $('dishNote').value.trim() }) closeSheet('dishSheet') paintCartBar() toast(`已加入:${currentDish.name} × ${draft.qty}`) }) // ---------- 购物车 ---------- function paintCartBar() { const cart = readCart() const sum = totals(cart, PROMOTIONS) $('cartbar').hidden = sum.count === 0 $('cartCount').textContent = String(sum.count) $('cartTotal').textContent = money(sum.payable) $('cartHint').textContent = sum.discount ? `已选 ${sum.count} 件 · 已减 ${money(sum.discount)}` : `已选 ${sum.count} 件` } function paintCartSheet() { const cart = readCart() const sum = totals(cart, PROMOTIONS) $('orderNote').value = cart.note ?? '' $('utensilsCount').textContent = String(cart.utensils ?? 0) $('cartList').innerHTML = cart.items.length === 0 ? '

购物车是空的,先点几道菜吧。

' : cart.items.map((item, index) => { const spec = [Object.entries(item.spec).map(([k, v]) => `${k}:${v}`).join(' '), item.extras.join(' ')] .filter(Boolean).join(' · ') return `
${item.emoji}
${esc(item.name)} ${esc(spec)}${item.note ? ` · ${esc(item.note)}` : ''}
${money(item.price * item.qty)}
${item.qty}
` }).join('') $('cartSums').innerHTML = `
小计${money(sum.subtotal)}
${sum.promo ? `
${esc(sum.promo.label)}−${money(sum.discount)}
` : ''}
餐具${cart.utensils ?? 0} 份
` $('cartPayable').textContent = money(sum.payable) $('submitOrder').disabled = cart.items.length === 0 } $('cartList').addEventListener('click', (event) => { const cart = readCart() const minus = event.target.closest('[data-minus]') const plus = event.target.closest('[data-plus]') const index = Number((minus ?? plus)?.dataset?.[minus ? 'minus' : 'plus']) if (Number.isNaN(index)) return const item = cart.items[index] if (!item) return changeQty(item.key, item.note, minus ? -1 : 1) paintCartSheet() paintCartBar() }) $('orderNote').addEventListener('input', () => { const cart = readCart() cart.note = $('orderNote').value writeCart(cart) }) $('utensilsPlus').addEventListener('click', () => { const cart = readCart() cart.utensils = Math.min(20, (cart.utensils ?? 0) + 1) writeCart(cart) $('utensilsCount').textContent = String(cart.utensils) paintCartSheet() }) $('utensilsMinus').addEventListener('click', () => { const cart = readCart() cart.utensils = Math.max(0, (cart.utensils ?? 0) - 1) writeCart(cart) $('utensilsCount').textContent = String(cart.utensils) paintCartSheet() }) $('clearCart').addEventListener('click', () => { clearCart() paintCartSheet() paintCartBar() toast('购物车已清空') }) $('cartbarMain').addEventListener('click', () => { if (!table) return chooseTable() paintCartSheet() openSheet('cartSheet') }) $('checkout').addEventListener('click', () => { if (!table) return chooseTable() paintCartSheet() openSheet('cartSheet') }) $('submitOrder').addEventListener('click', () => { const cart = readCart() if (cart.items.length === 0) return if (!table) return chooseTable() cart.note = $('orderNote').value.trim() writeCart(cart) const order = submitOrder(cart, { table, promotions: PROMOTIONS }) closeSheet('cartSheet') paintCartBar() showOrder(order.id) toast(`下单成功,单号 ${order.no}`) }) // ---------- 选桌 ---------- function chooseTable() { const tables = ['A1', 'A2', 'A3', 'A4', 'B1', 'B2', 'B3', 'B4', 'C1', 'C2', '大厅 5', '包间 1'] const html = tables.map((name) => ``).join('') openSheet('historySheet') $('historyList').innerHTML = `

扫桌上的码会自动带出桌号;也可以手动选:

${html}
` $('historyList').onclick = (event) => { const button = event.target.closest('[data-table]') if (!button) return table = button.dataset.table setTable(table) paintShop() closeSheet('historySheet') toast(`已选 ${table} 桌`) if (readCart().items.length) { paintCartSheet(); openSheet('cartSheet') } } } $('tableBtn').addEventListener('click', chooseTable) // ---------- 订单页 ---------- function showOrder(id) { activeOrderId = id paintOrder() $('orderPage').hidden = false } function paintOrder() { const order = orderById(activeOrderId) if (!order) { $('orderPage').hidden = true; return } const status = STATUS[order.status] ?? STATUS.new const steps = [['new', '已下单'], ['cooking', '制作中'], ['served', '已上齐']] const index = steps.findIndex(([key]) => key === order.status) const stepHtml = steps.map(([key, label], i) => `
${label}
`).join('') $('statusCard').innerHTML = `

${esc(status.text)}

${order.table} 桌 · 单号 ${order.no} · ${clock(order.createdAt)} 下单

${stepHtml}
` $('orderDetail').innerHTML = `

菜品

${order.items.map((item) => { const spec = [Object.entries(item.spec).map(([k, v]) => `${k}:${v}`).join(' '), item.extras.join(' ')] .filter(Boolean).join(' · ') return `
${esc(item.name)}${spec ? ` ${esc(spec)}` : ''} × ${item.qty} ${money(item.price * item.qty)}
` }).join('')} ${order.note ? `
备注${esc(order.note)}
` : ''}
小计${money(order.subtotal)}
${order.discount ? `
${esc(order.promoLabel)}−${money(order.discount)}
` : ''}
应付${money(order.payable)}
` $('urge').disabled = order.status === 'served' || order.status === 'closed' } $('orderBack').addEventListener('click', () => { $('orderPage').hidden = true }) $('addMore').addEventListener('click', () => { $('orderPage').hidden = true window.scrollTo({ top: 0, behavior: 'smooth' }) }) $('urge').addEventListener('click', () => { const order = orderById(activeOrderId) if (!order) return updateOrder(order.id, { urgedAt: Date.now() }) toast('已经提醒后厨,请稍等') }) $('orderList').addEventListener('click', () => { const orders = readOrders().filter((order) => order.table === table) $('historyList').innerHTML = orders.length === 0 ? '

本桌还没有订单。

' : orders.map((order) => { const status = STATUS[order.status] ?? STATUS.new return `
${order.no} 号单${clock(order.createdAt)} · ${order.items.length} 个菜 · ${money(order.payable)}
${status.text}
` }).join('') $('historyList').onclick = (event) => { const row = event.target.closest('[data-open]') if (!row) return closeSheet('historySheet') showOrder(row.dataset.open) } openSheet('historySheet') }) // ---------- 同步 ---------- watch(() => { paintCartBar() if (!$('cartSheet').hidden) paintCartSheet() if (activeOrderId && !$('orderPage').hidden) paintOrder() }) // ---------- 启动 ---------- table = getTable() paintShop() paintCats() paintMenu() paintCartBar() if (!table) setTimeout(chooseTable, 400) if (readCart().items.length) toast(`购物车里还有 ${totals(readCart(), PROMOTIONS).count} 件,继续点`) // 分类栏默认高亮第一个 document.querySelector('.cat')?.classList.add('on')