/* 金牛贷款档案 · 霜曜融合交互层(服务端渲染版) 行为模型与定版样板一致:属性驱动、事件委托、可打断。 */ "use strict"; const $ = (s, r) => (r || document).querySelector(s); const $$ = (s, r) => Array.from((r || document).querySelectorAll(s)); const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); const root = () => document.querySelector("[data-variant-root]"); /* ---------- 主题(日间 / 夜间,记住选择,无首屏闪白由页头内联脚本保证) ---------- */ const THEME_KEY = "jn_theme"; function currentTheme() { const r = root(); return r && r.getAttribute("data-theme") === "night" ? "night" : "day"; } function setTheme(next, animate = true) { if (next !== "day" && next !== "night") return; const r = root(); if (!r) return; const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches; if (animate && !reduce) { r.setAttribute("data-theme-anim", ""); setTimeout(() => r.removeAttribute("data-theme-anim"), 240); } if (next === "night") r.setAttribute("data-theme", "night"); else r.removeAttribute("data-theme"); try { localStorage.setItem(THEME_KEY, next); } catch (e) {} $$("[data-theme-btn]", r).forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.themeBtn === next))); $$("img[data-brand-logo]", r).forEach((img) => { const src = next === "night" ? img.dataset.logoNight : img.dataset.logoDay; if (src) img.src = src; }); } function syncThemeButtons() { setTheme(currentTheme(), false); } /* ---------- Toast(与定版同结构) ---------- */ const toastRoot = document.createElement("div"); document.addEventListener("DOMContentLoaded", () => document.body.appendChild(toastRoot)); function toast(msg) { toastRoot.innerHTML = `
${esc(msg)}
`; const t = toastRoot.querySelector(".toast"); requestAnimationFrame(() => requestAnimationFrame(() => t.removeAttribute("data-hidden"))); clearTimeout(toast._t); toast._t = setTimeout(() => t.setAttribute("data-hidden", ""), 2600); } window.jnToast = toast; /* ---------- 勾选:三态全选 + 零几何动效 + 批量条 ---------- */ function syncCheckAll() { const r = root(); if (!r) return; const all = $("[data-check-all]", r); if (!all) return; const boxes = $$("[data-check]", r); const n = boxes.filter((b) => b.checked).length; all.checked = n > 0 && n === boxes.length; all.indeterminate = n > 0 && n < boxes.length; const slot = $("[data-batch-slot]", r); if (slot) { slot.toggleAttribute("data-has-selection", n > 0); const cnt = $("[data-batch-count]", slot); if (cnt) cnt.textContent = n; slot.style.display = n > 0 ? "" : "none"; } } /* ---------- 抽屉(行点击 · 拉取服务端片段) ---------- */ let openArchiveId = null; function openDetail(id) { const r = root(); if (!r) return; openArchiveId = id; const d = $("[data-drawer]", r); fetch(`index.php?action=archive_detail&id=${encodeURIComponent(id)}&drawer=1`, { credentials: "same-origin" }) .then((res) => res.text()) .then((html) => { if (openArchiveId !== id) return; d.innerHTML = html; r.setAttribute("data-drawer-open", ""); d.setAttribute("data-open-state", ""); const c = $(".drawer-close", r); if (c) c.focus(); }) .catch(() => { location.href = `index.php?action=archive_detail&id=${encodeURIComponent(id)}`; }); } function switchDrawerTab(tab) { if (!openArchiveId) return; const r = root(); const d = $("[data-drawer]", r); fetch(`index.php?action=archive_detail&id=${encodeURIComponent(openArchiveId)}&drawer=1&dtab=${encodeURIComponent(tab)}`, { credentials: "same-origin" }) .then((res) => res.text()) .then((html) => { d.innerHTML = html; }) .catch(() => {}); } function closeOverlays() { const r = root(); if (!r) return; r.removeAttribute("data-drawer-open"); const d = $("[data-drawer]", r); if (d && d.hasAttribute("data-open-state")) { d.removeAttribute("data-dragging"); d.style.transform = "translateX(102%)"; setTimeout(() => { d.removeAttribute("data-open-state"); d.style.transform = ""; }, 460); } openArchiveId = null; } /* ---------- 弹层(导入等,服务端已渲染,切属性即可) ---------- */ let modalReturnFocus = null; let modalFocusTimer = null; let modalFocusTeardown = null; function cancelPendingModalFocus() { if (modalFocusTeardown) { modalFocusTeardown(); modalFocusTeardown = null; } if (modalFocusTimer != null) { clearTimeout(modalFocusTimer); modalFocusTimer = null; } } function openModal(name, trigger) { const r = root(); if (!r || !name) return; cancelPendingModalFocus(); modalReturnFocus = trigger || document.activeElement; r.setAttribute("data-modal-open", name); const card = r.querySelector(`.modal-card[data-modal="${name}"]`); const focusEl = card && ( card.querySelector("input:not([type=hidden]),select,textarea") || card.querySelector("button.btn--primary,button") ); if (!focusEl) return; let settled = false; const settle = () => { if (settled) return; settled = true; cancelPendingModalFocus(); if (r.getAttribute("data-modal-open") !== name) return; if (!document.contains(focusEl)) return; try { focusEl.focus(); } catch (e) {} }; const onEnd = (e) => { if (e.target !== card) return; settle(); }; card.addEventListener("transitionend", onEnd); modalFocusTeardown = () => card.removeEventListener("transitionend", onEnd); modalFocusTimer = setTimeout(settle, 250); } function closeModal() { cancelPendingModalFocus(); const r = root(); if (!r) return; const name = r.getAttribute("data-modal-open"); if (name) { const card = r.querySelector(`.modal-card[data-modal="${name}"]`); if (card) { card.querySelectorAll('input[type="password"]').forEach((i) => { i.value = ""; }); card.querySelectorAll(".form-field[data-error]").forEach((f) => f.removeAttribute("data-error")); card.querySelectorAll("[data-err], .field-err").forEach((el) => { el.textContent = ""; }); } } r.removeAttribute("data-modal-open"); const back = modalReturnFocus; modalReturnFocus = null; if (back && typeof back.focus === "function" && document.contains(back)) { try { back.focus(); } catch (e) {} } } /* ---------- 表单错误提示(与定版同结构) ---------- */ function setErr(input, msg) { const field = input.closest(".form-field"); if (msg) { input.setAttribute("aria-invalid", "true"); if (field) { field.setAttribute("data-error", ""); let e = field.querySelector("[data-err], .field-err"); if (!e) { e = document.createElement("div"); e.className = "field-err"; e.setAttribute("data-err", ""); field.appendChild(e); } e.textContent = msg; } else { let e = input.nextElementSibling; if (!(e && e.hasAttribute("data-jn-date-err"))) { e = document.createElement("div"); e.className = "field-err"; e.setAttribute("data-err", ""); e.setAttribute("data-jn-date-err", ""); input.insertAdjacentElement("afterend", e); } e.textContent = msg; } } else { input.removeAttribute("aria-invalid"); if (field) { field.removeAttribute("data-error"); const e = field.querySelector("[data-err], .field-err"); if (e) e.textContent = ""; } else { const e = input.nextElementSibling; if (e && e.hasAttribute("data-jn-date-err")) e.remove(); } } } window.jnSetErr = setErr; /* ============================================================ 计算器引擎(HEL-324/325 口径,与原系统一致,未删减) ============================================================ */ const CN_HOLIDAYS = (() => { const H2025 = ["2025-01-01","2025-01-28","2025-01-29","2025-01-30","2025-01-31","2025-02-01","2025-02-02","2025-02-03","2025-02-04","2025-04-04","2025-04-05","2025-04-06","2025-05-01","2025-05-02","2025-05-03","2025-05-04","2025-05-05","2025-05-31","2025-06-01","2025-06-02","2025-10-01","2025-10-02","2025-10-03","2025-10-04","2025-10-05","2025-10-06","2025-10-07","2025-10-08"]; const H2026 = ["2026-01-01","2026-01-02","2026-01-03","2026-02-15","2026-02-16","2026-02-17","2026-02-18","2026-02-19","2026-02-20","2026-02-21","2026-02-22","2026-02-23","2026-04-04","2026-04-05","2026-04-06","2026-05-01","2026-05-02","2026-05-03","2026-05-04","2026-05-05","2026-06-19","2026-06-20","2026-06-21","2026-09-25","2026-09-26","2026-09-27","2026-10-01","2026-10-02","2026-10-03","2026-10-04","2026-10-05","2026-10-06","2026-10-07"]; const S = {}; H2025.concat(H2026).forEach((x) => { S[x] = 1; }); return S; })(); const cPad = (n) => (n < 10 ? "0" : "") + n; const cYmd = (d) => d.getFullYear() + "-" + cPad(d.getMonth() + 1) + "-" + cPad(d.getDate()); function ymdParts(s) { const m = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(String(s || "").trim()); if (!m) return null; const y = +m[1], mo = +m[2], d = +m[3]; if (!y || mo < 1 || mo > 12 || d < 1) return null; const dt = new Date(y, mo - 1, d); if (dt.getFullYear() !== y || dt.getMonth() !== mo - 1 || dt.getDate() !== d) return null; return { y, mo, d, date: dt, ymd: y + "-" + cPad(mo) + "-" + cPad(d) }; } function cParseYmd(s) { const p = ymdParts(s); return p ? p.date : null; } function cIsNonWork(d) { const w = d.getDay(); return w === 0 || w === 6 || !!CN_HOLIDAYS[cYmd(d)]; } function cNextWorkday(ymdStr) { const d = cParseYmd(ymdStr); if (!d) return ymdStr; for (let i = 0; i < 20; i++) { if (!cIsNonWork(d)) return cYmd(d); d.setDate(d.getDate() + 1); } return cYmd(d); } function cAddMonths(y, m, day, add) { const nm = m - 1 + add, ny = y + Math.floor(nm / 12), nmo = ((nm % 12) + 12) % 12; const last = new Date(ny, nmo + 1, 0).getDate(); return new Date(ny, nmo, Math.min(day, last)); } function cNum(s) { s = String(s || "").replace(/,/g, "").trim(); if (s === "") return NaN; const v = parseFloat(s); return isFinite(v) ? v : NaN; } function cM2(n) { if (!isFinite(n)) return ""; const p = (Math.round(n * 100) / 100).toFixed(2).split("."); p[0] = p[0].replace(/\B(?=(\d{3})+(?!\d))/g, ","); return p.join("."); } function caps(n) { if (!(n > 0)) return "—"; const units = ["", "拾", "佰", "仟"], big = ["", "万", "亿"]; let integer = Math.floor(n), decimal = Math.round((n - integer) * 100); let s = "", i = 0; if (integer === 0) s = "零"; while (integer > 0) { let seg = integer % 10000, segStr = ""; for (let j = 0; seg > 0; j++) { const d = seg % 10; segStr = (d ? "零壹贰叁肆伍陆柒捌玖"[d] + units[j] : (segStr && !segStr.startsWith("零") ? "零" : "")) + segStr; seg = Math.floor(seg / 10); } s = segStr + big[i] + s; integer = Math.floor(integer / 10000); i++; } s += "元"; if (decimal === 0) s += "整"; else { const j = Math.floor(decimal / 10), f = decimal % 10; if (j) s += "零壹贰叁肆伍陆柒捌玖"[j] + "角"; if (f) s += "零壹贰叁肆伍陆柒捌玖"[f] + "分"; } return "人民币" + s; } function ciDaysFromRange(d1, d2, mode) { const a = ymdParts(d1), b = ymdParts(d2); if (!a || !b) return NaN; const t0 = new Date(a.ymd + "T12:00:00").getTime(), t1 = new Date(b.ymd + "T12:00:00").getTime(); if (t1 < t0) return NaN; const diff = Math.round((t1 - t0) / 86400000); return mode === "inclusive" ? diff + 1 : diff; } function renderInterest() { const r = root(); const f = r && $("[data-calc-interest]", r); if (!f) return; const slot = $("[data-ci-result]", r); const P = cNum(f.amt.value), rate = cNum(f.rate.value), kind = f.rateKind.value; const basis = f.basis.value, cm = f.countMode.value; const mode = (f.querySelector('input[name="ciDayMode"]:checked') || {}).value || "manual"; const fmtEl = $("[data-ci-fmt]", r), capEl = $("[data-ci-cap]", r); if (fmtEl) fmtEl.innerHTML = isFinite(P) && P > 0 ? `格式化:${cM2(P)} 元` : ""; if (capEl) capEl.innerHTML = isFinite(P) && P > 0 ? `· 大写:${caps(Math.floor(P)).replace(/^人民币/, "")}` : ""; const rangeLabel = $("[data-ci-range-label]", r); let days; if (mode === "manual") { const n = parseInt(f.days.value, 10); days = isFinite(n) && n >= 0 ? n : NaN; if (rangeLabel) rangeLabel.textContent = ""; } else { days = ciDaysFromRange(f.d1.value, f.d2.value, cm); if (rangeLabel) rangeLabel.textContent = isFinite(days) ? `→ 计息天数 ${days}` : ""; } const invalid = !(P > 0) ? "请输入有效本金" : !(rate > 0) ? "请输入有效利率" : (!isFinite(days) || days < 0) ? "请检查计息天数或起止日期" : ""; if (invalid) { window._ciLast = null; slot.innerHTML = `
计算结果
${invalid},结果区即时更新
`; return; } let interest, dref; if (kind === "annual") { interest = P * (rate / 100) * (days / +basis); dref = (rate / 100) / +basis; } else if (kind === "monthly") { interest = P * (rate / 100) * (days / 30); dref = (rate / 100) / 30; } else { interest = P * (rate / 100) * days; dref = rate / 100; } const total = P + interest; const kindTxt = { annual: "年利率", monthly: "月利率", daily: "日利率" }[kind]; const formula = kind === "annual" ? `${cM2(P)} × ${rate}% ÷ ${basis} × ${days} 天` : kind === "monthly" ? `${cM2(P)} × ${rate}% ÷ 30 × ${days} 天` : `${cM2(P)} × ${rate}% × ${days} 天`; window._ciLast = { text: `利息 ${cM2(interest)} 元 | 本息合计 ${cM2(total)} 元 | 天数 ${days}` }; slot.innerHTML = `
计算结果
应付利息
${cM2(interest)}
大写 ${caps(interest)}
本息合计${cM2(total)} 元
实际计息天数${days} 天
参考日利率${(dref * 100).toFixed(6)}%
参考日利率按当前利率种类换算,仅供参考 · ${kindTxt} ${rate}% · ${cm === "inclusive" ? "记首记尾" : "记首不记尾"} · ${basis} 天/年
${formula}
`; } /* — 利息计算器 · 分段累加(HEL-574):多笔支用 / 逾期分段变利率变本金 — */ function ciTopMode(r) { const b = $("[data-ci-mode][data-active]", r || root()); return b ? b.dataset.ciMode : "single"; } function setCIMode(mode) { const r = root(); if (!r) return; const next = mode === "multi" ? "multi" : "single"; $$("[data-ci-mode]", r).forEach((b) => { if (b.dataset.ciMode === next) b.setAttribute("data-active", ""); else b.removeAttribute("data-active"); }); const pS = $('[data-ci-panel="single"]', r), pM = $('[data-ci-panel="multi"]', r); if (pS) pS.hidden = next !== "single"; if (pM) pM.hidden = next !== "multi"; if (next === "multi") ensureCiSegRows(); initCalc(); } const CI_SEG_MAX = 20; function ciSegAddRow(focus) { const r = root(); const host = r && $("[data-ci-seg-rows]", r); const tpl = r && $("[data-ci-seg-tpl]", r); if (!host || !tpl) return null; if (host.children.length >= CI_SEG_MAX) { toast("最多支持 " + CI_SEG_MAX + " 段"); return null; } const row = tpl.content.firstElementChild.cloneNode(true); host.appendChild(row); if (focus !== false) { const inp = $('[data-seg-f="amt"]', row); if (inp) inp.focus(); } return row; } function ensureCiSegRows() { const r = root(); const host = r && $("[data-ci-seg-rows]", r); if (host && !host.children.length) { ciSegAddRow(false); ciSegAddRow(false); } } function ciSegSyncRowMode(row) { const m = ($('[data-seg-f="daymode"]', row) || {}).value || "manual"; const cManual = $('[data-seg-cell="manual"]', row), cRange = $('[data-seg-cell="range"]', row); if (cManual) cManual.hidden = m !== "manual"; if (cRange) cRange.hidden = m !== "range"; if (m === "manual") { ["d1", "d2"].forEach((k) => { const el = $(`[data-seg-f="${k}"]`, row); if (el) { el.value = ""; el.removeAttribute("aria-invalid"); } }); } else { const el = $('[data-seg-f="days"]', row); if (el) el.value = ""; } $$(".field-err", row).forEach((e) => e.remove()); } function ciSegDelRow(btn) { const row = btn.closest("[data-ci-seg-row]"); if (!row) return; const host = row.parentElement; if (host && host.children.length <= 1) { toast("至少保留一段"); return; } row.remove(); initCalc(); } function ciSegResetRows(r) { const host = $("[data-ci-seg-rows]", r); if (!host) return; $$("[data-ci-seg-row]", host).forEach((row, i) => { if (i > 1) { row.remove(); return; } ["amt", "rate", "days", "d1", "d2"].forEach((k) => { const el = $(`[data-seg-f="${k}"]`, row); if (el) { el.value = ""; el.removeAttribute("aria-invalid"); } }); const dm = $('[data-seg-f="daymode"]', row); if (dm) dm.value = "manual"; const kd = $('[data-seg-f="kind"]', row); if (kd) kd.value = "annual"; const out = $('[data-seg-out]', row); if (out) { out.textContent = ""; out.removeAttribute("data-bad"); } ciSegSyncRowMode(row); }); if (!host.children.length) { ciSegAddRow(false); ciSegAddRow(false); } } function ciSegRowDays(row, cm) { const m = ($('[data-seg-f="daymode"]', row) || {}).value || "manual"; if (m === "manual") { const n = parseInt(String($('[data-seg-f="days"]', row).value).trim(), 10); return isFinite(n) && n >= 0 ? { days: n } : { err: "请输入有效天数" }; } const d1 = $('[data-seg-f="d1"]', row).value, d2 = $('[data-seg-f="d2"]', row).value; const a = ymdParts(d1), b = ymdParts(d2); if (!a || !b) return { err: "起止日期不完整" }; const days = ciDaysFromRange(a.ymd, b.ymd, cm); return isFinite(days) && days >= 0 ? { days } : { err: "起止日期倒挂" }; } function renderInterestMulti() { const r = root(); const f = r && $("[data-calc-interest]", r); if (!f) return; const slot = $("[data-ci-result]", r); ensureCiSegRows(); const cm = f.countMode.value, basis = f.basis.value; const rows = $$("[data-ci-seg-row]", f); const segs = []; let firstErr = ""; rows.forEach((row, i) => { const no = i + 1; const amtEl = $('[data-seg-f="amt"]', row), rateEl = $('[data-seg-f="rate"]', row); const P = cNum(amtEl.value), rate = cNum(rateEl.value); const kind = $('[data-seg-f="kind"]', row).value; const res = ciSegRowDays(row, cm); const out = $('[data-seg-out]', row); const blank = !["amt", "rate", "days", "d1", "d2"].some((k) => String($(`[data-seg-f="${k}"]`, row).value).trim() !== ""); let rowErr = ""; if (blank) rowErr = `第 ${no} 段为空行,请填写或删除`; else if (!(P > 0)) rowErr = `第 ${no} 段:请输入有效本金`; else if (!(rate > 0)) rowErr = `第 ${no} 段:请输入有效利率`; else if (res.err) rowErr = `第 ${no} 段:${res.err}`; if (out) { if (blank) { out.textContent = "空行"; out.setAttribute("data-bad", ""); } else if (res.err) { out.textContent = res.err; out.setAttribute("data-bad", ""); } else { out.textContent = `→ ${res.days} 天`; out.removeAttribute("data-bad"); } } if (rowErr) { if (!firstErr) firstErr = rowErr; return; } const divisor = kind === "annual" ? +basis : kind === "monthly" ? 30 : 1; segs.push({ no, P, rate, kind, days: res.days, interest: P * (rate / 100) * (res.days / divisor) }); }); if (firstErr || !segs.length) { window._ciLast = null; slot.innerHTML = `
计算结果
${esc(firstErr || "请至少填写一段有效数据")},请修正后再计算
`; return; } const interestSum = segs.reduce((s, x) => s + x.interest, 0); const principalSum = segs.reduce((s, x) => s + x.P, 0); const total = principalSum + interestSum; const detail = segs.map((s) => { const div = s.kind === "annual" ? ` ÷ ${basis} ` : s.kind === "monthly" ? " ÷ 30 " : " "; return `
第 ${s.no} 段:${cM2(s.P)} × ${s.rate}%${div}× ${s.days} 天 = ${cM2(s.interest)} 元
`; }).join(""); window._ciLast = { text: `分段利息合计 ${cM2(interestSum)} 元 | 本金合计 ${cM2(principalSum)} 元 | 本息合计 ${cM2(total)} 元 | 共 ${segs.length} 段(${segs.map((s) => `第${s.no}段 ${cM2(s.P)}×${s.rate}%×${s.days}天=${cM2(s.interest)}`).join(";")})` }; slot.innerHTML = `
计算结果
利息合计
${cM2(interestSum)}
大写 ${caps(interestSum)}
${detail}
本金合计(${segs.length} 段)${cM2(principalSum)} 元
本息合计${cM2(total)} 元
${cm === "inclusive" ? "记首记尾" : "记首不记尾"} · ${basis} 天/年 · 年利率 ÷${basis}、月利率 ÷30、日利率直乘 · 各段独立计息后汇总
`; } /* — 承兑贴现计算器 — */ function dcHist() { try { const raw = localStorage.getItem("dc_hist_v1"); if (raw) return JSON.parse(raw); } catch (e) {} return []; } function dcHistSave(arr) { try { localStorage.setItem("dc_hist_v1", JSON.stringify(arr.slice(0, 30))); } catch (e) {} } function fmtWanShort(n) { return n >= 10000 ? (n / 10000).toFixed(2).replace(/\.00$/, "") + " 万" : cM2(n); } function renderDcHist() { const box = document.querySelector("[data-dc-hist]"); if (!box) return; const arr = dcHist(); box.innerHTML = arr.length ? arr.map((h, i) => `
${fmtWanShort(h.face)} · ${(+h.rate).toFixed(2)}%
${h.t} · ${h.days} 天
${cM2(h.net)}
`).join("") : `
暂无历史记录,计算后点击「保存记录」
`; } function renderDiscount() { const r = root(); const f = r && $("[data-calc-discount]", r); if (!f) return; const slot = $("[data-cd-result]", r); if (!f.now.value) { const t = new Date(); f.now.value = cYmd(t); } const face = cNum(f.face.value); const fmtEl = $("[data-cd-fmt]", r), capEl = $("[data-cd-cap]", r); if (fmtEl) fmtEl.innerHTML = isFinite(face) && face > 0 ? `格式化:${cM2(face)} 元` : ""; if (capEl) capEl.innerHTML = isFinite(face) && face > 0 ? `· 大写:${caps(Math.floor(face)).replace(/^人民币/, "")}` : ""; const matMode = (f.querySelector('input[name="cdMatMode"]:checked') || {}).value || "date"; const holiday = $("[data-cd-holiday]", r)?.getAttribute("aria-checked") === "true"; const remote = $("[data-cd-remote]", r)?.getAttribute("aria-checked") === "true"; const rule = f.rule.value; const dis = f.now.value, mat = f.due.value; const invalid0 = !(face > 0) ? "票面金额须大于 0" : (matMode === "after" && !mat) ? "请先「推算到期日」或改选指定到期日" : (!dis || !mat) ? "请完善贴现日与到期日" : ""; if (invalid0) { window._dcLast = null; slot.innerHTML = `
计算结果
${invalid0}
`; return; } const matEff = holiday ? cNextWorkday(mat) : mat; const d0 = cParseYmd(dis), d1 = cParseYmd(matEff); const rawDiff = d0 && d1 ? Math.round((d1 - d0) / 86400000) : NaN; const base = rule === "inclusive" ? rawDiff + 1 : rawDiff; const days = isFinite(base) && base >= 0 ? base + (remote ? 3 : 0) : NaN; if (!isFinite(days) || days <= 0) { window._dcLast = null; slot.innerHTML = `
计算结果
贴现日须早于到期日,且计息天数须为正
`; return; } const shiftDays = Math.max(0, Math.round(((cParseYmd(matEff) || 0) - (cParseYmd(mat) || 0)) / 86400000)); const netIn = cNum(f.netIn.value), per10 = cNum(f.per10.value); let rate = cNum(f.rate.value), interest, revLine = ""; if (isFinite(netIn) && netIn > 0 && netIn < face) { rate = (face - netIn) * 360 / (face * days) * 100; if (!isFinite(rate) || !(rate > 0)) { slot.innerHTML = `
计算结果
无法根据实付金额反推利率,请检查天数与金额
`; window._dcLast = null; return; } interest = face - netIn; f.rate.value = rate.toFixed(4); revLine = `已按实付金额反推贴现年利率:${rate.toFixed(4)}%`; } else if (isFinite(per10) && per10 > 0) { interest = per10 * (face / 100000); rate = (interest * 360 / (face * days)) * 100; if (!isFinite(rate) || !(rate > 0)) { slot.innerHTML = `
计算结果
无法根据每10万扣息反推利率
`; window._dcLast = null; return; } f.rate.value = rate.toFixed(4); revLine = `已按每10万扣息反推贴现年利率:${rate.toFixed(4)}%`; } else { if (!(rate > 0)) { slot.innerHTML = `
计算结果
请输入贴现年利率,或填写反推字段
`; window._dcLast = null; return; } interest = face * (rate / 100) * (days / 360); } const net = face - interest; const ann = net > 0 ? (interest / net) * (360 / days) * 100 : NaN; const p10 = face > 0 ? interest / (face / 100000) : NaN; const dayNote = (remote ? "(含异地+3天)" : "") + (holiday ? ";到期日已按工作日顺延" : ""); window._dcLast = { face, intr: interest, net, days, rate: (+rate).toFixed(4), text: `票面 ${(face / 10000).toFixed(2)}万 | 贴现息 ${cM2(interest)}元 | 实付 ${cM2(net)}元 | 天数 ${days}天` }; slot.innerHTML = `
计算结果
实付金额
${cM2(net)}
大写 ${caps(net)}
贴现利息${cM2(interest)} 元
贴现天数${days} 天 ${dayNote}
天数拆解计息 ${base}${shiftDays ? `(含顺延 ${shiftDays})` : ""}${remote ? " + 异地 3" : ""}
年化成本率${isFinite(ann) ? ann.toFixed(4) + "%" : "—"}
每10万扣息${isFinite(p10) ? cM2(p10) + " 元" : "—"}
${shiftDays ? `
到期日顺延至${matEff}
` : ""} ${revLine ? `
${revLine}
` : ""}
票据类型:${(f.querySelector('input[name="cdBill"]:checked') || {}).value === "commercial" ? "商业承兑汇票" : "银行承兑汇票"} · ${rule === "inclusive" ? "记首记尾" : "记首不记尾"} · 360 天/年
${cM2(face)} × ${(+rate).toFixed(4)}% ÷ 360 × ${days} 天 = ${cM2(interest)}
`; } function syncCalcModeRows(target) { const r = root(); if (!r) return; const ci = $("[data-calc-interest]", r); if (ci && target.name === "ciDayMode") { const m = (ci.querySelector('input[name="ciDayMode"]:checked') || {}).value; $('[data-ci-row="manual"]', r).hidden = m !== "manual"; $('[data-ci-row="range"]', r).hidden = m !== "range"; } const segRow = target.closest && target.closest("[data-ci-seg-row]"); if (segRow && target.getAttribute("data-seg-f") === "daymode") ciSegSyncRowMode(segRow); const cd = $("[data-calc-discount]", r); if (cd && target.name === "cdMatMode") { const m = (cd.querySelector('input[name="cdMatMode"]:checked') || {}).value; $('[data-cd-row="date"]', r).hidden = m !== "date"; $('[data-cd-row="after"]', r).hidden = m !== "after"; } if (cd && target.name === "cdBill") { const v = (cd.querySelector('input[name="cdBill"]:checked') || {}).value; const hint = $("[data-cd-bill-hint]", r); if (hint) hint.textContent = v === "bank" ? "银承:流通性较好,贴现利率通常低于商承。" : "商承:请重点评估承兑人信用;贴现利率通常高于银承。"; } } function applyCdMonths() { const r = root(); const f = r && $("[data-calc-discount]", r); if (!f) return; if (f.issue && isDateField(f.issue) && !applyDateValue(f.issue).ok) return; const iss = f.issue.value; if (!iss) { toast("请先填出票日"); return; } const mo = parseInt(f.months.value, 10); if (!(mo >= 1 && mo <= 12)) { toast("期限月数须为 1-12"); return; } const p = iss.split("-").map(Number); const d = cAddMonths(p[0], p[1], p[2], mo); f.due.value = cYmd(d); const pv = $("[data-cd-mat-preview]", r); if (pv) pv.textContent = "推算到期:" + cYmd(d); initCalc(); } function histRefill(i) { const r = root(); const f = r && $("[data-calc-discount]", r); if (!f) return; const h = dcHist()[i]; if (!h) return; f.face.value = h.face; f.rate.value = h.rate; initCalc(); toast("已回填票面金额与利率"); } function calcAction(act) { const r = root(); if (!r) return; const cd = $("[data-calc-discount]", r); if (act === "calc") { const form = $("[data-calc-interest]", r) || $("[data-calc-discount]", r); if (form && !normalizeFormDates(form)) return; initCalc(); return; } if (act === "reset") { const ci = $("[data-calc-interest]", r); if (ci) { ci.amt.value = ""; ci.rate.value = ""; ci.days.value = ""; ci.d1.value = ""; ci.d2.value = ""; [ci.d1, ci.d2].forEach((el) => { if (el) setErr(el, ""); }); ciSegResetRows(r); initCalc(); toast("已重置"); return; } const cd2 = $("[data-calc-discount]", r); if (cd2) { cd2.face.value = ""; cd2.rate.value = ""; cd2.issue.value = ""; cd2.due.value = ""; cd2.netIn.value = ""; cd2.per10.value = ""; [cd2.issue, cd2.now, cd2.due].forEach((el) => { if (el) setErr(el, ""); }); const pv = $("[data-cd-mat-preview]", r); if (pv) pv.textContent = ""; initCalc(); toast("已重置"); return; } return; } if (act === "copy") { const last = cd ? window._dcLast : window._ciLast; if (!last) { toast("请先完成一次有效计算"); return; } const txt = last.text; if (navigator.clipboard) navigator.clipboard.writeText(txt).then(() => toast("结果已复制"), () => toast(txt)); else toast(txt); return; } if (act === "save" && cd) { if (!window._dcLast) { toast("请先完成一次有效计算"); return; } const arr = dcHist(); const l = window._dcLast; arr.unshift({ t: new Date().toLocaleString("zh-CN", { hour12: false }), face: l.face, rate: l.rate, days: l.days, intr: l.intr, net: l.net }); dcHistSave(arr); renderDcHist(); toast("已保存到本地历史"); } } function initCalc() { const r = root(); if (!r) return; if ($("[data-calc-interest]", r)) { ciTopMode(r) === "multi" ? renderInterestMulti() : renderInterest(); } if ($("[data-calc-discount]", r)) { renderDiscount(); renderDcHist(); } } /* ============================================================ HEL-349 · 自定义锚定弹层(下拉 / 日历) 原生 select 展开列表与 input[type=date] 日历无法可靠换肤/定位, 用现有 fusion 栈做 fixed 锚定层;原生控件仍负责取值与提交。 ============================================================ */ const WEEKDAYS = ["日", "一", "二", "三", "四", "五", "六"]; let popHost = null; let menuEl = null; let dpEl = null; let dirPopEl = null; let popAnchor = null; let popKind = null; let dpView = null; let dpFocusYmd = null; let popRepositionBound = false; let dirPickerItems = []; let dirExpanded = new Set(); function popRoot() { return root() || document.body; } function ensurePops() { const host = popRoot(); if (popHost === host && menuEl && dpEl && dirPopEl) return; popHost = host; if (menuEl && menuEl.parentNode) menuEl.remove(); if (dpEl && dpEl.parentNode) dpEl.remove(); if (dirPopEl && dirPopEl.parentNode) dirPopEl.remove(); menuEl = document.createElement("div"); menuEl.id = "jn-select-menu"; menuEl.className = "jn-pop jn-menu"; menuEl.hidden = true; menuEl.setAttribute("role", "listbox"); menuEl.setAttribute("tabindex", "-1"); dpEl = document.createElement("div"); dpEl.id = "jn-datepicker"; dpEl.className = "jn-pop jn-dp"; dpEl.hidden = true; dpEl.setAttribute("role", "dialog"); dpEl.setAttribute("aria-label", "选择日期"); dirPopEl = document.createElement("div"); dirPopEl.id = "jn-dir-picker"; dirPopEl.className = "jn-pop dir-picker-pop"; dirPopEl.hidden = true; dirPopEl.setAttribute("role", "tree"); dirPopEl.setAttribute("aria-label", "选择归档目录"); host.appendChild(menuEl); host.appendChild(dpEl); host.appendChild(dirPopEl); } function placePopover(pop, anchor) { const gap = 6, margin = 8; pop.hidden = false; pop.style.top = "0px"; pop.style.left = "0px"; const ar = anchor.getBoundingClientRect(); const pr = pop.getBoundingClientRect(); const vw = window.innerWidth, vh = window.innerHeight; let top = ar.bottom + gap; if (top + pr.height > vh - margin && ar.top - gap - pr.height >= margin) { top = ar.top - gap - pr.height; } top = Math.min(Math.max(margin, top), Math.max(margin, vh - pr.height - margin)); let left = ar.left; if (left + pr.width > vw - margin) left = vw - pr.width - margin; left = Math.max(margin, left); pop.style.top = Math.round(top) + "px"; pop.style.left = Math.round(left) + "px"; if (pop === menuEl) { pop.style.minWidth = Math.round(ar.width) + "px"; pop.style.maxWidth = Math.min(480, vw - margin * 2) + "px"; } if (pop === dirPopEl) { pop.style.minWidth = Math.round(Math.max(ar.width, 280)) + "px"; pop.style.maxWidth = Math.min(420, vw - margin * 2) + "px"; } } function repositionOpenPop() { if (!popAnchor || !popKind) return; const pop = popKind === "menu" ? menuEl : popKind === "dir" ? dirPopEl : dpEl; if (!pop || pop.hidden) return; if (!popAnchor.isConnected) { closePops(); return; } placePopover(pop, popAnchor); } function bindPopReposition(on) { if (on && !popRepositionBound) { window.addEventListener("resize", repositionOpenPop); window.addEventListener("scroll", repositionOpenPop, true); popRepositionBound = true; } else if (!on && popRepositionBound) { window.removeEventListener("resize", repositionOpenPop); window.removeEventListener("scroll", repositionOpenPop, true); popRepositionBound = false; } } function closePops() { const prev = popAnchor; const kind = popKind; const ae = document.activeElement; const focusBack = !!(prev && ae && (ae === prev || (menuEl && menuEl.contains(ae)) || (dpEl && dpEl.contains(ae)) || (dirPopEl && dirPopEl.contains(ae)))); if (menuEl) { menuEl.hidden = true; menuEl.innerHTML = ""; } if (dpEl) dpEl.hidden = true; if (dirPopEl) { dirPopEl.hidden = true; dirPopEl.innerHTML = ""; } if (prev) { prev.setAttribute("aria-expanded", "false"); prev.removeAttribute("aria-controls"); } popAnchor = null; popKind = null; bindPopReposition(false); if (focusBack) prev.focus(); return !!kind; } function nativeSelect(el) { return el && el.tagName === "SELECT" && !el.multiple && !(+el.size > 1); } function openSelectMenu(select) { if (!nativeSelect(select) || select.disabled) return; ensurePops(); if (popKind === "menu" && popAnchor === select) { closePops(); return; } closePops(); popAnchor = select; popKind = "menu"; select.setAttribute("aria-expanded", "true"); select.setAttribute("aria-controls", "jn-select-menu"); menuEl.innerHTML = ""; const opts = Array.from(select.options); opts.forEach((opt, i) => { const btn = document.createElement("button"); btn.type = "button"; btn.className = "jn-menu-opt"; btn.setAttribute("role", "option"); btn.dataset.index = String(i); btn.textContent = opt.textContent; if (opt.disabled) { btn.disabled = true; btn.setAttribute("aria-disabled", "true"); } if (opt.selected) btn.setAttribute("aria-selected", "true"); menuEl.appendChild(btn); }); placePopover(menuEl, select); bindPopReposition(true); const active = menuEl.querySelector(".jn-menu-opt[aria-selected='true']:not(:disabled)") || menuEl.querySelector(".jn-menu-opt:not(:disabled)"); if (active) active.focus(); } function commitSelect(index) { const select = popAnchor; if (!nativeSelect(select)) { closePops(); return; } const opt = select.options[index]; if (!opt || opt.disabled) return; if (select.selectedIndex !== index) { select.selectedIndex = index; select.dispatchEvent(new Event("input", { bubbles: true })); select.dispatchEvent(new Event("change", { bubbles: true })); } closePops(); select.focus(); } function dirParentId(item) { return +(item && item.parent_id ? item.parent_id : 0); } function dirByParentMap() { const map = new Map(); dirPickerItems.forEach((it) => { const pid = dirParentId(it); if (!map.has(pid)) map.set(pid, []); map.get(pid).push(it); }); return map; } function dirItemById(id) { id = +id; return dirPickerItems.find((it) => +it.id === id) || null; } function dirAncestorIds(id) { const out = []; let cur = dirItemById(id); while (cur) { const pid = dirParentId(cur); if (!pid) break; out.push(pid); cur = dirItemById(pid); } return out; } function seedDirExpanded(selectedId) { dirExpanded = new Set(dirAncestorIds(selectedId).map(String)); } function dirChevron() { const ns = "http://www.w3.org/2000/svg"; const svg = document.createElementNS(ns, "svg"); svg.setAttribute("class", "dir-tree-chevron"); svg.setAttribute("width", "12"); svg.setAttribute("height", "12"); svg.setAttribute("viewBox", "0 0 12 12"); svg.setAttribute("aria-hidden", "true"); const path = document.createElementNS(ns, "path"); path.setAttribute("d", "M4.25 2.5 8.25 6l-4 3.5"); path.setAttribute("fill", "none"); path.setAttribute("stroke", "currentColor"); path.setAttribute("stroke-width", "1.5"); path.setAttribute("stroke-linecap", "round"); path.setAttribute("stroke-linejoin", "round"); svg.appendChild(path); return svg; } function dirAllButton(selectedId) { const wrap = document.createElement("div"); wrap.className = "dir-picker-reset"; const btn = document.createElement("button"); btn.type = "button"; btn.className = "jn-menu-opt dir-picker-opt"; btn.setAttribute("role", "treeitem"); btn.setAttribute("aria-level", "1"); btn.dataset.id = "0"; const name = document.createElement("span"); name.className = "dir-picker-opt-name"; name.textContent = "全部目录"; btn.appendChild(name); if (+selectedId === 0) btn.setAttribute("aria-selected", "true"); wrap.appendChild(btn); return wrap; } function dirTreeRow(item, selectedId, hasKids, expanded) { const row = document.createElement("div"); row.className = "dir-tree-row"; row.style.setProperty("--dir-indent", String(Math.max(0, (item.level || 1) - 1))); if (hasKids) { const tog = document.createElement("button"); tog.type = "button"; tog.className = "dir-tree-toggle"; tog.dataset.dirToggle = String(item.id); tog.setAttribute("aria-expanded", expanded ? "true" : "false"); tog.setAttribute("aria-label", (expanded ? "收起 " : "展开 ") + item.name); tog.appendChild(dirChevron()); row.appendChild(tog); } else { const sp = document.createElement("span"); sp.className = "dir-tree-toggle is-leaf"; sp.setAttribute("aria-hidden", "true"); row.appendChild(sp); } const btn = document.createElement("button"); btn.type = "button"; btn.className = "jn-menu-opt dir-picker-opt"; btn.setAttribute("role", "treeitem"); btn.setAttribute("aria-level", String(item.level || 1)); btn.dataset.id = String(item.id); if (hasKids) btn.setAttribute("aria-expanded", expanded ? "true" : "false"); btn.title = item.path || item.name; const name = document.createElement("span"); name.className = "dir-picker-opt-name"; name.textContent = item.name; btn.appendChild(name); if (+selectedId === +item.id) btn.setAttribute("aria-selected", "true"); row.appendChild(btn); return row; } function renderDirPicker() { if (!dirPopEl) return; const wrap = popAnchor && popAnchor.closest("[data-dir-picker]"); const selectedId = wrap ? +(wrap.dataset.selected || 0) : 0; const byParent = dirByParentMap(); dirPopEl.innerHTML = ""; const list = document.createElement("div"); list.className = "dir-picker-list"; list.appendChild(dirAllButton(selectedId)); const walk = (parentId) => { (byParent.get(parentId) || []).forEach((it) => { const kids = byParent.get(+it.id) || []; const expanded = dirExpanded.has(String(it.id)); list.appendChild(dirTreeRow(it, selectedId, kids.length > 0, expanded)); if (kids.length && expanded) walk(+it.id); }); }; walk(0); dirPopEl.appendChild(list); } function dirPickerOptions() { return dirPopEl ? $$(".dir-picker-opt", dirPopEl) : []; } function dirPickerFocusables() { if (!dirPopEl) return []; return $$("button:not([disabled])", dirPopEl); } function restoreDirFocus(id, wantToggle) { if (!dirPopEl || id == null) return; const sel = wantToggle ? dirPopEl.querySelector(`[data-dir-toggle="${id}"]`) : dirPopEl.querySelector(`.dir-picker-opt[data-id="${id}"]`); if (sel) sel.focus(); } function toggleDirExpand(id, force) { const key = String(id); const open = force === true ? true : force === false ? false : !dirExpanded.has(key); if (open) dirExpanded.add(key); else dirExpanded.delete(key); const ae = document.activeElement; const keepId = ae && dirPopEl && dirPopEl.contains(ae) ? (ae.dataset.dirToggle || ae.dataset.id) : key; const wantToggle = !!(ae && ae.hasAttribute && ae.hasAttribute("data-dir-toggle")); renderDirPicker(); if (popAnchor) placePopover(dirPopEl, popAnchor); restoreDirFocus(keepId, wantToggle); } function moveDirHighlight(delta) { const opts = dirPickerOptions(); if (!opts.length) return; const cur = opts.findIndex((el) => el === document.activeElement || el.classList.contains("is-active")); const next = delta > 0 ? (cur + 1) % opts.length : (cur <= 0 ? opts.length - 1 : cur - 1); opts.forEach((el) => el.classList.remove("is-active")); opts[next].classList.add("is-active"); opts[next].focus(); } function dirOptHasKids(id) { const kids = dirByParentMap().get(+id); return !!(kids && kids.length); } function openDirPicker(trigger) { if (!trigger) return; const wrap = trigger.closest("[data-dir-picker]"); if (!wrap) return; ensurePops(); if (popKind === "dir" && popAnchor === trigger) { closePops(); return; } closePops(); try { dirPickerItems = JSON.parse(wrap.getAttribute("data-dirs") || "[]"); } catch (e) { dirPickerItems = []; } if (!Array.isArray(dirPickerItems)) dirPickerItems = []; seedDirExpanded(+(wrap.dataset.selected || 0)); popAnchor = trigger; popKind = "dir"; trigger.setAttribute("aria-expanded", "true"); trigger.setAttribute("aria-controls", "jn-dir-picker"); renderDirPicker(); placePopover(dirPopEl, trigger); bindPopReposition(true); const selected = dirPopEl.querySelector(".dir-picker-opt[aria-selected='true']") || dirPopEl.querySelector(".dir-picker-opt"); if (selected) { selected.focus(); selected.scrollIntoView({ block: "nearest" }); } } function commitDirPicker(id) { const trigger = popAnchor; const wrap = trigger && trigger.closest("[data-dir-picker]"); const form = wrap && wrap.closest("form"); const hidden = wrap && wrap.querySelector('input[name="dir_id"]'); if (!hidden || !form) { closePops(); return; } hidden.value = String(id || 0); closePops(); form.submit(); } function parseLimit(v) { const s = String(v || "").trim(); return /^\d{4}-\d{2}-\d{2}$/.test(s) ? s : ""; } function inDateRange(ymd, min, max) { if (min && ymd < min) return false; if (max && ymd > max) return false; return true; } function isDateField(el) { return !!(el && el.tagName === "INPUT" && (el.type === "date" || el.hasAttribute("data-jn-date"))); } function dateFieldMin(input) { return parseLimit(input.getAttribute("data-min") || input.min); } function dateFieldMax(input) { return parseLimit(input.getAttribute("data-max") || input.max); } function applyDateValue(input, opts) { const fire = !opts || opts.fire !== false; const raw = String(input.value || "").trim(); if (raw === "") { if (input.value !== "") input.value = ""; setErr(input, ""); return { ok: true, ymd: "" }; } const parsed = ymdParts(raw); if (!parsed) { setErr(input, "请输入有效日期(YYYY-MM-DD)"); return { ok: false, ymd: "" }; } const min = dateFieldMin(input), max = dateFieldMax(input); const changed = input.value !== parsed.ymd; if (changed) input.value = parsed.ymd; if (!inDateRange(parsed.ymd, min, max)) { if (changed && fire) { input.dispatchEvent(new Event("input", { bubbles: true })); input.dispatchEvent(new Event("change", { bubbles: true })); } setErr(input, "日期超出允许范围"); return { ok: false, ymd: parsed.ymd }; } setErr(input, ""); if (changed && fire) { input.dispatchEvent(new Event("input", { bubbles: true })); input.dispatchEvent(new Event("change", { bubbles: true })); } return { ok: true, ymd: parsed.ymd }; } function normalizeFormDates(form) { if (!form) return true; let ok = true, firstBad = null; form.querySelectorAll('input[data-jn-date], input[type="date"]').forEach((input) => { if (input.disabled) return; const r = applyDateValue(input); if (!r.ok) { ok = false; if (!firstBad) firstBad = input; } }); if (firstBad) { try { firstBad.scrollIntoView({ block: "center", behavior: "smooth" }); firstBad.focus(); } catch (e) {} } return ok; } function yearBounds(input) { const now = new Date().getFullYear(); let yMin = now - 40, yMax = now + 20; const min = dateFieldMin(input), max = dateFieldMax(input); if (min) yMin = parseInt(min.slice(0, 4), 10); if (max) yMax = parseInt(max.slice(0, 4), 10); if (yMin > yMax) yMax = yMin; return { yMin, yMax }; } function ymDisabled(y, m, min, max) { const start = y + "-" + cPad(m + 1) + "-01"; const end = y + "-" + cPad(m + 1) + "-" + cPad(new Date(y, m + 1, 0).getDate()); if (min && end < min) return true; if (max && start > max) return true; return false; } function yearDisabled(y, min, max) { if (min && y < parseInt(min.slice(0, 4), 10)) return true; if (max && y > parseInt(max.slice(0, 4), 10)) return true; return false; } function armDateInput(input) { if (!isDateField(input) || input.dataset.jnArmed === "1") return; input.dataset.jnArmed = "1"; if (input.type === "date") { const v = input.value; const min = input.getAttribute("min") || ""; const max = input.getAttribute("max") || ""; input.type = "text"; input.setAttribute("data-jn-date", ""); if (min) input.setAttribute("data-min", min); if (max) input.setAttribute("data-max", max); input.removeAttribute("min"); input.removeAttribute("max"); if (v) input.value = v; } if (!input.getAttribute("inputmode")) input.setAttribute("inputmode", "numeric"); input.setAttribute("autocomplete", "off"); input.setAttribute("spellcheck", "false"); if (!input.getAttribute("placeholder")) input.setAttribute("placeholder", "YYYY-MM-DD"); input.setAttribute("maxlength", "10"); input.classList.add("num"); } function enhanceDateInputs(scope) { const host = scope && scope.querySelectorAll ? scope : document; host.querySelectorAll('input[type="date"], input[data-jn-date]').forEach(armDateInput); } let dpMode = "day"; let dpYearPage = null; let dpFocusPick = null; function renderDatePicker() { if (!dpEl || !popAnchor) return; const input = popAnchor; const min = dateFieldMin(input), max = dateFieldMax(input); const selected = (ymdParts(input.value) || {}).ymd || ""; const today = cYmd(new Date()); if (!dpView) { const seed = cParseYmd(selected) || new Date(); dpView = { y: seed.getFullYear(), m: seed.getMonth() }; } if (!dpFocusYmd) dpFocusYmd = selected || today; const y = dpView.y, m = dpView.m; const { yMin, yMax } = yearBounds(input); if (!dpYearPage) dpYearPage = Math.floor(y / 12) * 12; dpYearPage = Math.min(Math.max(dpYearPage, yMin), Math.max(yMin, yMax - 11)); const navLabel = dpMode === "year" ? "年" : (dpMode === "month" ? "年" : "月"); let body = ""; if (dpMode === "year") { let cells = ""; for (let i = 0; i < 12; i++) { const yy = dpYearPage + i; const disabled = yy < yMin || yy > yMax || yearDisabled(yy, min, max); const sel = yy === y; const isFocus = dpFocusPick === yy; cells += ``; } body = `
${cells}
`; } else if (dpMode === "month") { let cells = ""; for (let i = 0; i < 12; i++) { const disabled = ymDisabled(y, i, min, max); const sel = i === m; const isFocus = dpFocusPick === i; cells += ``; } body = `
${cells}
`; } else { const first = new Date(y, m, 1); const startDow = first.getDay(); const gridStart = new Date(y, m, 1 - startDow); let days = ""; for (let i = 0; i < 42; i++) { const d = new Date(gridStart.getFullYear(), gridStart.getMonth(), gridStart.getDate() + i); const ymd = cYmd(d); const out = d.getMonth() !== m; const disabled = !inDateRange(ymd, min, max); const sel = selected && ymd === selected; const isFocus = ymd === dpFocusYmd; days += ``; } body = `
${WEEKDAYS.map((w) => `${w}`).join("")}
${days}
`; } dpEl.innerHTML = `
${body}
`; let focusBtn = null; if (dpMode === "year") { focusBtn = dpEl.querySelector(`.jn-dp-pick[data-dp-year="${dpFocusPick}"]:not(:disabled)`) || dpEl.querySelector(".jn-dp-pick:not(:disabled)"); } else if (dpMode === "month") { focusBtn = dpEl.querySelector(`.jn-dp-pick[data-dp-month="${dpFocusPick}"]:not(:disabled)`) || dpEl.querySelector(".jn-dp-pick:not(:disabled)"); } else { focusBtn = dpEl.querySelector(`.jn-dp-day[data-ymd="${dpFocusYmd}"]:not(:disabled)`) || dpEl.querySelector(".jn-dp-day:not(:disabled)"); if (focusBtn) dpFocusYmd = focusBtn.dataset.ymd; } if (focusBtn) { focusBtn.tabIndex = 0; focusBtn.focus(); } } function openDatePicker(input) { if (!isDateField(input) || input.disabled || input.readOnly) return; armDateInput(input); ensurePops(); if (popKind === "date" && popAnchor === input) { closePops(); return; } closePops(); popAnchor = input; popKind = "date"; dpMode = "day"; input.setAttribute("aria-expanded", "true"); input.setAttribute("aria-controls", "jn-datepicker"); input.setAttribute("aria-haspopup", "dialog"); const seed = cParseYmd(input.value) || new Date(); dpView = { y: seed.getFullYear(), m: seed.getMonth() }; dpFocusYmd = parseLimit(input.value) || cYmd(new Date()); dpYearPage = Math.floor(dpView.y / 12) * 12; dpFocusPick = dpView.y; renderDatePicker(); placePopover(dpEl, input); bindPopReposition(true); } function commitDate(ymd) { const input = popAnchor; if (!isDateField(input)) { closePops(); return; } if (ymd === "") { if (input.value !== "") { input.value = ""; input.dispatchEvent(new Event("input", { bubbles: true })); input.dispatchEvent(new Event("change", { bubbles: true })); } setErr(input, ""); closePops(); input.focus(); return; } const min = dateFieldMin(input), max = dateFieldMax(input); if (!inDateRange(ymd, min, max)) return; if (input.value !== ymd) { input.value = ymd; input.dispatchEvent(new Event("input", { bubbles: true })); input.dispatchEvent(new Event("change", { bubbles: true })); } setErr(input, ""); closePops(); input.focus(); } function shiftDpFocus(days) { const cur = cParseYmd(dpFocusYmd) || new Date(); cur.setDate(cur.getDate() + days); dpFocusYmd = cYmd(cur); dpView = { y: cur.getFullYear(), m: cur.getMonth() }; renderDatePicker(); repositionOpenPop(); } function shiftDpMonth(delta) { if (!dpView) return; const d = new Date(dpView.y, dpView.m + delta, 1); dpView = { y: d.getFullYear(), m: d.getMonth() }; const keep = cParseYmd(dpFocusYmd) || d; const last = new Date(dpView.y, dpView.m + 1, 0).getDate(); const day = Math.min(keep.getDate(), last); dpFocusYmd = cYmd(new Date(dpView.y, dpView.m, day)); renderDatePicker(); repositionOpenPop(); } function shiftDpNav(delta) { if (dpMode === "year") { const { yMin, yMax } = yearBounds(popAnchor); dpYearPage = Math.min(Math.max((dpYearPage || yMin) + delta * 12, yMin), Math.max(yMin, yMax - 11)); dpFocusPick = Math.min(Math.max((dpFocusPick || dpView.y) + delta * 12, yMin), yMax); renderDatePicker(); repositionOpenPop(); return; } if (dpMode === "month") { if (!dpView) return; dpView = { y: dpView.y + delta, m: dpView.m }; dpFocusPick = dpView.m; renderDatePicker(); repositionOpenPop(); return; } shiftDpMonth(delta); } if (typeof HTMLInputElement !== "undefined" && HTMLInputElement.prototype.showPicker) { const nativeShowPicker = HTMLInputElement.prototype.showPicker; HTMLInputElement.prototype.showPicker = function () { if (isDateField(this) && this.closest("[data-variant-root]")) { openDatePicker(this); return; } return nativeShowPicker.call(this); }; } document.addEventListener("mousedown", (e) => { const t = e.target; if (dirPopEl && !dirPopEl.hidden && dirPopEl.contains(t)) return; const dirTrig = t.closest && t.closest("[data-dir-picker-trigger]"); if (dirTrig && dirTrig.closest("[data-variant-root]")) { e.preventDefault(); dirTrig.focus(); openDirPicker(dirTrig); return; } if (menuEl && !menuEl.hidden && menuEl.contains(t)) return; if (dpEl && !dpEl.hidden && dpEl.contains(t)) return; const dateInp = t.closest && t.closest("input"); if (dateInp && isDateField(dateInp) && dateInp.closest("[data-variant-root]")) { if (dateInp.disabled || dateInp.readOnly) return; e.preventDefault(); armDateInput(dateInp); dateInp.focus(); openDatePicker(dateInp); return; } const sel = t.closest && t.closest("select"); if (sel && nativeSelect(sel) && sel.closest("[data-variant-root]")) { if (sel.disabled) return; e.preventDefault(); sel.focus(); openSelectMenu(sel); return; } if (popKind) closePops(); }, true); document.addEventListener("click", (e) => { const dateInp = e.target.closest && e.target.closest("input"); if (dateInp && isDateField(dateInp) && dateInp.closest("[data-variant-root]")) { e.preventDefault(); } }, true); document.addEventListener("click", (e) => { const t = e.target; if (!dpEl || dpEl.hidden || !dpEl.contains(t)) return; const nav = t.closest("[data-dp-nav]"); if (nav) { shiftDpNav(+nav.dataset.dpNav); return; } const viewBtn = t.closest("[data-dp-view]"); if (viewBtn) { const next = viewBtn.dataset.dpView; dpMode = dpMode === next ? "day" : next; dpFocusPick = dpMode === "year" ? dpView.y : dpView.m; renderDatePicker(); repositionOpenPop(); return; } const yPick = t.closest("[data-dp-year]"); if (yPick && !yPick.disabled) { dpView = { y: +yPick.dataset.dpYear, m: dpView.m }; dpMode = "month"; dpFocusPick = dpView.m; renderDatePicker(); repositionOpenPop(); return; } const mPick = t.closest("[data-dp-month]"); if (mPick && !mPick.disabled) { dpView = { y: dpView.y, m: +mPick.dataset.dpMonth }; dpMode = "day"; const keep = cParseYmd(dpFocusYmd) || new Date(dpView.y, dpView.m, 1); const last = new Date(dpView.y, dpView.m + 1, 0).getDate(); dpFocusYmd = cYmd(new Date(dpView.y, dpView.m, Math.min(keep.getDate(), last))); renderDatePicker(); repositionOpenPop(); return; } if (t.closest("[data-dp-clear]")) { commitDate(""); return; } if (t.closest("[data-dp-today]")) { const today = cYmd(new Date()); const input = popAnchor; const min = input ? dateFieldMin(input) : ""; const max = input ? dateFieldMax(input) : ""; if (inDateRange(today, min, max)) commitDate(today); return; } const day = t.closest(".jn-dp-day"); if (day && !day.disabled) commitDate(day.dataset.ymd); }); document.addEventListener("click", (e) => { const t = e.target; if (!menuEl || menuEl.hidden || !menuEl.contains(t)) return; const opt = t.closest(".jn-menu-opt"); if (opt && !opt.disabled) commitSelect(+opt.dataset.index); }); document.addEventListener("click", (e) => { const t = e.target; if (!dirPopEl || dirPopEl.hidden || !dirPopEl.contains(t)) return; const tog = t.closest("[data-dir-toggle]"); if (tog) { e.preventDefault(); toggleDirExpand(tog.dataset.dirToggle); return; } const opt = t.closest(".dir-picker-opt"); if (opt && !opt.disabled) commitDirPicker(+opt.dataset.id); }); /* ---------- 事件委托 ---------- */ document.addEventListener("click", (e) => { const t = e.target; const themeBtn = t.closest("[data-theme-btn]"); if (themeBtn) { setTheme(themeBtn.dataset.themeBtn); return; } const scope = t.closest("[data-search-scope]"); if (scope) { const form = scope.closest("form"); const input = form && form.querySelector('input[name="q"]'); const hidden = form && form.querySelector('input[name="search_field"]'); if (form && input && hidden && input.value !== input.defaultValue) { e.preventDefault(); hidden.value = scope.dataset.searchScope; form.submit(); return; } } const copyBtn = t.closest("[data-copy-text]"); if (copyBtn) { const txt = copyBtn.dataset.copyText; if (navigator.clipboard) navigator.clipboard.writeText(txt).then(() => toast("大写金额已复制"), () => toast(txt)); else toast(txt); return; } const checkAll = t.closest("[data-check-all]"); if (checkAll) { e.stopPropagation(); $$("[data-check]", root()).forEach((b) => { b.checked = checkAll.checked; const tr = b.closest("tr"); if (tr) tr.toggleAttribute("data-checked", checkAll.checked); }); syncCheckAll(); return; } const check = t.closest("[data-check]"); if (check) { e.stopPropagation(); const tr = check.closest("tr"); if (tr) tr.toggleAttribute("data-checked", check.checked); syncCheckAll(); return; } if (t.closest("[data-clear-check]")) { $$("[data-check]", root()).forEach((b) => { b.checked = false; const tr = b.closest("tr"); if (tr) tr.removeAttribute("data-checked"); }); const all = $("[data-check-all]", root()); if (all) { all.checked = false; all.indeterminate = false; } syncCheckAll(); return; } const sw = t.closest("[data-switch]"); if (sw) { sw.setAttribute("aria-checked", String(sw.getAttribute("aria-checked") !== "true")); initCalc(); return; } const ciModeBtn = t.closest("[data-ci-mode]"); if (ciModeBtn) { setCIMode(ciModeBtn.dataset.ciMode); return; } if (t.closest("[data-ci-seg-add]")) { ciSegAddRow(); initCalc(); return; } const ciSegDel = t.closest("[data-ci-seg-del]"); if (ciSegDel) { ciSegDelRow(ciSegDel); return; } const calcAct = t.closest("[data-calc-act]"); if (calcAct) { calcAction(calcAct.dataset.calcAct); return; } const refRate = t.closest("[data-ref-rate]"); if (refRate) { const f = refRate.closest("form"); if (f && f.rate) { f.rate.value = refRate.dataset.refRate; initCalc(); } return; } if (t.closest("[data-apply-months]")) { applyCdMonths(); return; } const histFill = t.closest("[data-hist-fill]"); if (histFill) { histRefill(+histFill.dataset.histFill); return; } if (t.closest("[data-hist-clear]")) { dcHistSave([]); renderDcHist(); toast("本地历史已清空"); return; } const dtab = t.closest("[data-dtab]"); if (dtab) { switchDrawerTab(dtab.dataset.dtab); return; } const openModalBtn = t.closest("[data-open-modal]"); if (openModalBtn) { openModal(openModalBtn.dataset.openModal, openModalBtn); return; } if (t.closest("[data-close-modal]")) { closeModal(); return; } if (t.closest(".dir-acts")) return; const opener = t.closest("[data-open-detail]"); if (opener) { if (!t.closest("a,button,input,select,textarea,label")) openDetail(opener.dataset.openDetail); return; } if (t.closest("[data-close-drawer]")) { closeOverlays(); return; } }); document.addEventListener("change", (e) => { if (e.target.closest("[data-calc-interest]") || e.target.closest("[data-calc-discount]")) { syncCalcModeRows(e.target); initCalc(); } }); document.addEventListener("input", (e) => { if (e.target.closest(".form-field") || isDateField(e.target)) setErr(e.target, ""); if (e.target.closest("[data-calc-interest]") || e.target.closest("[data-calc-discount]")) { const ci = e.target.closest("[data-calc-interest]"); if (ci) { if (e.target.id === "ci-days" && e.target.value) { ci.d1.value = ""; ci.d2.value = ""; const l = $("[data-ci-range-label]", root()); if (l) l.textContent = ""; } if ((e.target.id === "ci-d1" || e.target.id === "ci-d2") && e.target.value) { ci.days.value = ""; } } initCalc(); } }); document.addEventListener("keydown", (e) => { if (e.key === "Enter" && e.target.matches && e.target.matches("[data-open-detail]")) openDetail(e.target.dataset.openDetail); if (e.target.matches && e.target.matches("a.dir-row") && (e.key === "Enter" || e.key === " ")) { if (e.key === " ") { e.preventDefault(); e.target.click(); } } if (e.target.closest && e.target.closest("[data-dir-picker-trigger]") && (e.key === "ArrowDown" || e.key === "Enter" || e.key === " ")) { e.preventDefault(); openDirPicker(e.target.closest("[data-dir-picker-trigger]")); return; } if (popKind === "dir" && dirPopEl && !dirPopEl.hidden) { const opts = dirPickerOptions(); const focusables = dirPickerFocusables(); const activeOpt = document.activeElement && document.activeElement.classList.contains("dir-picker-opt") ? document.activeElement : (dirPopEl.querySelector(".dir-picker-opt.is-active") || null); const activeId = activeOpt ? +activeOpt.dataset.id : 0; if (e.key === "Escape") { e.preventDefault(); closePops(); return; } if (e.key === "ArrowDown") { e.preventDefault(); moveDirHighlight(1); return; } if (e.key === "ArrowUp") { e.preventDefault(); moveDirHighlight(-1); return; } if (e.key === "ArrowRight" && activeId) { e.preventDefault(); if (dirOptHasKids(activeId) && !dirExpanded.has(String(activeId))) toggleDirExpand(activeId, true); else moveDirHighlight(1); return; } if (e.key === "ArrowLeft") { e.preventDefault(); if (activeId && dirExpanded.has(String(activeId))) { toggleDirExpand(activeId, false); return; } const parentId = activeId ? dirParentId(dirItemById(activeId)) : 0; if (parentId) restoreDirFocus(parentId, false); else restoreDirFocus(0, false); return; } if (e.key === "Home" && opts[0]) { e.preventDefault(); opts.forEach((el) => el.classList.remove("is-active")); opts[0].classList.add("is-active"); opts[0].focus(); return; } if (e.key === "End" && opts.length) { e.preventDefault(); opts.forEach((el) => el.classList.remove("is-active")); opts[opts.length - 1].classList.add("is-active"); opts[opts.length - 1].focus(); return; } if (e.key === "Enter" || e.key === " ") { const tog = e.target.closest && e.target.closest("[data-dir-toggle]"); if (tog) { e.preventDefault(); toggleDirExpand(tog.dataset.dirToggle); return; } const hit = (e.target.classList && e.target.classList.contains("dir-picker-opt") && dirPopEl.contains(e.target)) ? e.target : (dirPopEl.querySelector(".dir-picker-opt.is-active") || opts[0]); if (hit) { e.preventDefault(); commitDirPicker(+hit.dataset.id); } return; } if (e.key === "Tab") { const i = focusables.indexOf(document.activeElement); if (e.shiftKey) { if (i <= 0) { e.preventDefault(); closePops(); } } else if (i === -1 || i >= focusables.length - 1) { e.preventDefault(); closePops(); } return; } } if (popKind === "menu" && menuEl && !menuEl.hidden) { const opts = $$(".jn-menu-opt:not(:disabled)", menuEl); if (e.key === "Escape") { e.preventDefault(); closePops(); return; } if (e.key === "ArrowDown" || e.key === "ArrowUp") { e.preventDefault(); if (!opts.length) return; const cur = opts.indexOf(document.activeElement); const next = e.key === "ArrowDown" ? (cur + 1) % opts.length : (cur <= 0 ? opts.length - 1 : cur - 1); opts[next].focus(); return; } if (e.key === "Home" && opts[0]) { e.preventDefault(); opts[0].focus(); return; } if (e.key === "End" && opts.length) { e.preventDefault(); opts[opts.length - 1].focus(); return; } if ((e.key === "Enter" || e.key === " ") && document.activeElement && document.activeElement.classList.contains("jn-menu-opt")) { e.preventDefault(); commitSelect(+document.activeElement.dataset.index); return; } if (e.key === "Tab") { closePops(); return; } } if (popKind === "date" && dpEl && !dpEl.hidden) { if (e.key === "Escape") { e.preventDefault(); closePops(); return; } if (e.key === "Tab") { e.preventDefault(); closePops(); return; } if (dpMode === "year" || dpMode === "month") { const picks = $$(".jn-dp-pick:not(:disabled)", dpEl); if (e.key === "ArrowLeft" || e.key === "ArrowRight" || e.key === "ArrowUp" || e.key === "ArrowDown") { e.preventDefault(); if (!picks.length) return; const cols = 3; const cur = picks.indexOf(document.activeElement); const i = cur < 0 ? 0 : cur; let next = i; if (e.key === "ArrowLeft") next = i <= 0 ? picks.length - 1 : i - 1; if (e.key === "ArrowRight") next = (i + 1) % picks.length; if (e.key === "ArrowUp") next = (i - cols + picks.length) % picks.length; if (e.key === "ArrowDown") next = (i + cols) % picks.length; picks[next].focus(); dpFocusPick = dpMode === "year" ? +picks[next].dataset.dpYear : +picks[next].dataset.dpMonth; return; } if ((e.key === "Enter" || e.key === " ") && document.activeElement && document.activeElement.classList.contains("jn-dp-pick") && !document.activeElement.disabled) { e.preventDefault(); document.activeElement.click(); return; } if (e.key === "PageUp") { e.preventDefault(); shiftDpNav(-1); return; } if (e.key === "PageDown") { e.preventDefault(); shiftDpNav(1); return; } } else { if (e.key === "ArrowLeft") { e.preventDefault(); shiftDpFocus(-1); return; } if (e.key === "ArrowRight") { e.preventDefault(); shiftDpFocus(1); return; } if (e.key === "ArrowUp") { e.preventDefault(); shiftDpFocus(-7); return; } if (e.key === "ArrowDown") { e.preventDefault(); shiftDpFocus(7); return; } if (e.key === "PageUp") { e.preventDefault(); shiftDpMonth(-1); return; } if (e.key === "PageDown") { e.preventDefault(); shiftDpMonth(1); return; } if (e.key === "Home") { e.preventDefault(); shiftDpFocus(-((cParseYmd(dpFocusYmd) || new Date()).getDay())); return; } if (e.key === "End") { e.preventDefault(); shiftDpFocus(6 - ((cParseYmd(dpFocusYmd) || new Date()).getDay())); return; } if (e.key === "Enter" && document.activeElement && document.activeElement.classList.contains("jn-dp-day") && !document.activeElement.disabled) { e.preventDefault(); commitDate(document.activeElement.dataset.ymd); return; } } } const dateInp = e.target.closest && e.target.closest("input"); if (dateInp && isDateField(dateInp) && !dateInp.disabled && (e.key === "ArrowDown" || e.key === " " || (e.altKey && e.key === "ArrowDown"))) { e.preventDefault(); openDatePicker(dateInp); return; } const sel = e.target.closest && e.target.closest("select"); if (nativeSelect(sel) && !sel.disabled && (e.key === "ArrowDown" || e.key === "ArrowUp" || e.key === " " || e.key === "Enter")) { e.preventDefault(); openSelectMenu(sel); return; } if (e.key === "Escape") { if (closePops()) return; closeOverlays(); closeModal(); } }); /* — 抽屉拖拽关闭(1:1 跟手 + 速度判定 + 边界阻尼) — */ let drag = null; document.addEventListener("pointerdown", (e) => { const grip = e.target.closest("[data-grip]"); const r = root(); if (!grip || !r) return; if (drag) return; drag = { startX: e.clientX, dx: 0, v: 0, lastX: e.clientX, lastT: performance.now() }; $("[data-drawer]", r).setAttribute("data-dragging", ""); grip.setPointerCapture?.(e.pointerId); }); document.addEventListener("pointermove", (e) => { if (!drag) return; const now = performance.now(); const dt = Math.max(now - drag.lastT, 1); drag.v = 0.7 * drag.v + 0.3 * ((e.clientX - drag.lastX) / dt); drag.lastX = e.clientX; drag.lastT = now; let dx = e.clientX - drag.startX; if (dx < 0) dx = dx * 0.25; drag.dx = dx; const d = $("[data-drawer]", root()); if (d) d.style.transform = `translateX(${dx}px)`; }); function endDrag() { if (!drag) return; const d = $("[data-drawer]", root()); if (d) { d.removeAttribute("data-dragging"); if (drag.dx > 110 || drag.v > 0.11) closeOverlays(); else d.style.transform = "translateX(0)"; } drag = null; } document.addEventListener("pointerup", endDrag); document.addEventListener("pointercancel", endDrag); /* — 按住确认(慢填充 1.4s linear / 松手回弹;按住完成后提交目标表单) — */ let holdTimer = null; document.addEventListener("pointerdown", (e) => { const btn = e.target.closest("[data-hold-delete]"); if (!btn) return; btn.setAttribute("data-holding", ""); clearTimeout(holdTimer); holdTimer = setTimeout(() => { btn.removeAttribute("data-holding"); const sel = btn.dataset.holdDelete; const form = sel && sel !== "1" ? document.querySelector(sel) : btn.closest("form"); if (form) form.submit(); else toast("已确认"); }, 1400); }); ["pointerup", "pointerleave", "pointercancel"].forEach((ev) => document.addEventListener(ev, (e) => { const btn = e.target.closest && e.target.closest("[data-hold-delete]"); if (btn) { clearTimeout(holdTimer); btn.removeAttribute("data-holding"); } }) ); document.addEventListener("focusout", (e) => { const input = e.target; if (!isDateField(input) || input.disabled || input.readOnly) return; const next = e.relatedTarget; if (dpEl && next && dpEl.contains(next)) return; applyDateValue(input); }); document.addEventListener("submit", (e) => { const form = e.target; if (!form || form.tagName !== "FORM") return; if (!normalizeFormDates(form)) { e.preventDefault(); e.stopPropagation(); } }, true); /* ---------- 启动 ---------- */ document.addEventListener("DOMContentLoaded", () => { syncThemeButtons(); syncCheckAll(); initCalc(); enhanceDateInputs(); const mo = new MutationObserver((recs) => { recs.forEach((r) => { r.addedNodes.forEach((n) => { if (n.nodeType !== 1) return; if (isDateField(n)) armDateInput(n); else enhanceDateInputs(n); }); }); }); mo.observe(document.body, { childList: true, subtree: true }); });