html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>货架货物管理系统</title>
<style>
/* 基础重置 */
* {
margin: 0; padding: 0; box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
}
html, body, #app {
height: 100%;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
background: #f5faff;
color: #333;
user-select: none;
}
/* 主题色与变量 */
:root {
--color-main: rgba(133, 183, 235, 0.55);
--color-main-alpha: rgba(133, 183, 235, 0.35);
--color-silver-gray: #aaaeb2;
--color-silver-gray-light: #dde2e6;
--color-white-grad: linear-gradient(135deg, #ffffffdd 0%, #eaf2fcdd 100%);
--color-black-trans: rgba(0,0,0,0.65);
--color-shadow: rgba(0,0,0,0.12);
--color-shadow-deep: rgba(0,0,0,0.24);
--btn-radius: 8px;
--transition-speed: 0.25s;
--font-size-base: 14px;
--font-size-md: 16px;
--font-size-lg: 18px;
}
/* 禁止文本选中可取消此处 */
input, button, select, textarea {
user-select: text;
}
/* 整体布局 */
#app {
display: flex;
height: 100vh;
overflow: hidden;
background: var(--color-white-grad);
position: relative;
}
/* 侧边栏 */
#sidebar {
width: 280px;
max-width: 280px;
min-width: 56px;
background: var(--color-main);
backdrop-filter: blur(12px);
color: #30445d;
display: flex;
flex-direction: column;
box-shadow: 3px 0 8px var(--color-shadow);
transition: width var(--transition-speed) ease;
position: relative;
z-index: 10;
}
#sidebar.collapsed {
width: 56px;
}
/* 侧边栏顶部logo */
#sidebar-header {
height: 72px;
min-height: 72px;
padding: 10px 16px;
display: flex;
align-items: center;
gap: 12px;
border-bottom: 1px solid var(--color-silver-gray-light);
background: var(--color-main-alpha);
}
#sidebar-logo-wrapper {
position: relative;
width: 44px;
height: 44px;
border-radius: 8px;
overflow: hidden;
background: rgba(255 255 255 / 0.68);
cursor: pointer;
flex-shrink: 0;
}
#sidebar-logo-wrapper img, #sidebar-logo-wrapper svg {
width: 100%;
height: 100%;
object-fit: contain;
display: block;
}
#sidebar-header h1 {
font-weight: 700;
font-size: var(--font-size-lg);
color: #1b2b41;
white-space: nowrap;
flex: 1;
user-select: none;
transition: opacity var(--transition-speed);
}
#sidebar.collapsed #sidebar-header h1 {
opacity: 0;
pointer-events: none;
}
/* Logo上传input隐藏 */
#logo-upload {
display: none;
}
/* 货架列表 */
#shelf-list {
flex: 1;
overflow-y: auto;
padding: 8px 8px 56px 8px;
}
#shelf-list ul {
list-style: none;
}
#shelf-list li {
margin-bottom: 6px;
}
/* 单个货架项 */
.shelf-item {
user-select: none;
background: rgba(255 255 255 / 0.65);
border-radius: 8px;
padding: 6px 12px;
display: flex;
align-items: center;
gap: 12px;
cursor: pointer;
transition:
background-color 0.2s ease,
box-shadow 0.3s ease;
position: relative;
box-shadow: 0 2px 4px var(--color-shadow);
}
.shelf-item.selected {
background: #78a9f9cc;
color: white;
box-shadow: 0 2px 8px #5190f9cc;
}
/* 折叠状态仅显示图标(缩略字母) */
#sidebar.collapsed .shelf-item span.name {
display: none;
}
/* 货架名字编辑 */
.shelf-item input.rename-input {
flex: 1;
font-size: var(--font-size-md);
border: none;
background: transparent;
color: #1b2b41;
outline: none;
border-radius: 6px;
padding: 2px 4px;
}
/* 操作按钮组 */
.shelf-buttons {
display: flex;
gap: 6px;
flex-shrink: 0;
}
/* 删除只对空货架启用 */
.shelf-buttons button {
background: transparent;
border: none;
color: var(--color-silver-gray);
cursor: pointer;
border-radius: 50%;
width: 24px;
height: 24px;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
transition: color 0.2s ease;
}
.shelf-buttons button:disabled {
cursor: not-allowed;
color: #bbb;
}
.shelf-buttons button:hover:not(:disabled) {
color: #f44336;
}
/* 删除按钮SVG */
.icon-delete {
width: 18px;
height: 18px;
fill: currentColor;
}
/* 编辑按钮 */
.icon-edit {
width: 18px;
height: 18px;
fill: currentColor;
}
/* 底部折叠按钮 */
#sidebar-footer {
height: 56px;
border-top: 1px solid var(--color-silver-gray-light);
background: var(--color-main-alpha);
display: flex;
justify-content: center;
align-items: center;
}
#sidebar-toggle-btn {
background: transparent;
border: none;
cursor: pointer;
width: 36px;
height: 36px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
color: #30445d;
transition: background-color 0.2s ease, color 0.25s ease;
position: relative;
overflow: hidden;
}
#sidebar-toggle-btn:hover {
background-color: #d6e8ff88;
color: #1967d2;
}
#sidebar-toggle-btn:focus {
outline: 2px solid #1967d2;
outline-offset: 2px;
}
/* 折叠图标旋转 */
#sidebar.collapsed #sidebar-toggle-icon {
transform: rotate(180deg);
}
#sidebar-toggle-icon {
width: 24px;
height: 24px;
stroke-width: 2.2;
stroke: currentColor;
fill: none;
transition: transform 0.3s ease;
}
/* 右侧主区域 */
#main-area {
flex: 1;
display: flex;
flex-direction: column;
position: relative;
overflow: hidden;
background-color: #ffffffdd;
backdrop-filter: blur(6px);
}
/* 背景 */
#background-layer {
position: absolute;
inset: 0;
overflow: hidden;
z-index: 0;
}
#background-image {
position: absolute;
inset: 0;
object-fit: cover;
width: 100%;
height: 100%;
filter: brightness(0.85);
user-select: none;
pointer-events: none;
}
#particle-canvas {
position: absolute;
inset: 0;
z-index: 1;
pointer-events: none;
}
/* 工具栏 */
#toolbar {
position: relative;
padding: 10px 16px;
background: rgba(255 255 255 / 0.85);
border-bottom: 1px solid var(--color-silver-gray-light);
display: flex;
gap: 16px;
align-items: center;
z-index: 10;
}
#search-input {
flex: 1;
height: 36px;
border-radius: var(--btn-radius);
border: 1.5px solid var(--color-silver-gray-light);
padding: 0 12px;
font-size: var(--font-size-md);
transition: border-color 0.25s ease;
}
#search-input:focus {
border-color: #6ea0ff;
outline: none;
}
/* 文件操作按钮统一 */
.operation-btn {
height: 36px;
padding: 0 12px;
background: var(--color-main);
border: none;
border-radius: var(--btn-radius);
color: #fff;
font-weight: 600;
cursor: pointer;
box-shadow: 0 2px 4px var(--color-shadow);
user-select: none;
display: flex;
align-items: center;
gap: 6px;
transition:
background-color 0.25s ease,
box-shadow 0.2s ease;
}
.operation-btn:hover, .operation-btn:focus {
background: #4285f4;
box-shadow: 0 4px 8px var(--color-shadow-deep);
outline: none;
}
.operation-btn:disabled {
cursor: not-allowed;
background: #aac8f5;
box-shadow: none;
color: #e1eaf7;
}
.operation-btn svg {
width: 18px;
height: 18px;
stroke-width: 2;
stroke: currentColor;
}
/* 文件上传input隐藏 */
#file-import-input {
display: none;
}
/* 货物表格 */
#goods-table-wrapper {
flex: 1;
overflow: auto;
padding: 12px 20px 24px 20px;
background-color: rgba(255 255 255 / 0.7);
backdrop-filter: saturate(180%) blur(6px);
box-shadow: inset 0 0 16px #cbe1ff55;
border-radius: 8px 0 0 8px;
}
#goods-table {
width: 100%;
border-collapse: collapse;
min-width: 600px;
}
#goods-table thead tr {
background: var(--color-main);
color: white;
user-select: none;
}
#goods-table thead th {
padding: 12px 10px;
font-weight: 700;
font-size: var(--font-size-md);
text-align: left;
border-bottom: 2px solid #ffffffdd;
}
#goods-table tbody tr {
background: #ffffffbb;
cursor: pointer;
transition: background-color 0.15s ease;
}
#goods-table tbody tr:hover {
background: #c6ddfbcc;
}
#goods-table tbody tr.selected {
background: #1e3a8add;
color: white;
}
#goods-table tbody td {
padding: 10px 8px;
font-size: var(--font-size-base);
vertical-align: middle;
border-bottom: 1px solid #dce9fc;
position: relative;
}
#goods-table tbody td img.thumb {
width: 52px;
height: 40px;
object-fit: contain;
border-radius: 4px;
cursor: pointer;
border: 1.5px solid var(--color-silver-gray-light);
background: white;
display: block;
}
#goods-table tbody td .thumb-placeholder {
width: 52px;
height: 40px;
border-radius: 4px;
border: 1.5px solid var(--color-silver-gray-light);
background: repeating-linear-gradient(
45deg,
#d0d6de,
#d0d6de 4px,
#ecf0fc 4px,
#ecf0fc 8px
);
display: flex;
justify-content: center;
align-items: center;
color: #a0a7b3;
font-weight: 600;
font-size: 18px;
user-select: none;
}
/* 表格复选框 */
#goods-table tbody td input[type="checkbox"] {
transform: scale(1.15);
cursor: pointer;
margin: 0;
}
/* 操作按钮区 */
#action-buttons {
padding: 10px 20px;
background: rgba(255 255 255 / 0.85);
border-top: 1px solid var(--color-silver-gray-light);
display: flex;
gap: 14px;
justify-content: start;
user-select: none;
box-shadow: inset 0 8px 10px -10px #7ba3ea44;
}
#action-buttons button {
padding: 10px 18px;
border-radius: var(--btn-radius);
font-size: var(--font-size-md);
color: white;
border: none;
cursor: pointer;
min-width: 110px;
box-shadow: 0 3px 6px var(--color-shadow-deep);
position: relative;
overflow: hidden;
transition: background-color 0.3s ease, box-shadow 0.2s ease;
font-weight: 600;
}
#action-buttons button:disabled {
background: #aac8f5;
cursor: not-allowed;
box-shadow: none;
}
#btn-add {
background: #4285f4;
}
#btn-edit {
background: #1a73e8;
}
#btn-delete {
background: #f44336;
}
#btn-move {
background: #4caf50;
}
#action-buttons button:hover:not(:disabled),
#action-buttons button:focus:not(:disabled) {
box-shadow: 0 6px 12px var(--color-shadow-deep);
filter: brightness(1.05);
outline: none;
}
/* 波纹容器 */
#action-buttons button .ripple {
position: absolute;
border-radius: 50%;
background-color: rgba(255 255 255 / 0.5);
transform: scale(0);
animation: ripple-effect 0.6s linear;
pointer-events: none;
z-index: 10;
}
@keyframes ripple-effect {
to {
transform: scale(4);
opacity: 0;
}
}
/* 音效按钮隐藏,音频播放器 */
audio {
display: none;
}
/* 添加/编辑货物模态弹窗 */
#modal-backdrop {
position: fixed;
inset: 0;
background: rgba(10,14,30,0.85);
display: none;
align-items: center;
justify-content: center;
z-index: 1000;
user-select: text;
}
#modal-backdrop.active {
display: flex;
}
#modal-panel {
background: #1e263a;
border-radius: 20px;
padding: 28px 32px;
width: 420px;
max-width: 90vw;
box-shadow: 0 8px 30px #0a142ecc;
color: white;
display: flex;
flex-direction: column;
gap: 16px;
position: relative;
}
#modal-panel h2 {
margin-bottom: 8px;
font-weight: 700;
}
#modal-panel label {
font-weight: 600;
font-size: var(--font-size-md);
user-select: none;
margin-bottom: 4px;
display: block;
}
#modal-panel input[type="text"],
#modal-panel input[type="number"],
#modal-panel select,
#modal-panel textarea {
width: 100%;
height: 32px;
border-radius: var(--btn-radius);
border: none;
padding: 0 10px;
font-size: var(--font-size-md);
background: #2f3a57;
color: white;
outline: none;
transition: background-color 0.25s ease;
}
#modal-panel textarea {
height: 80px;
resize: vertical;
padding-top: 8px;
}
#modal-panel input[type="file"] {
padding: 4px 0;
border-radius: var(--btn-radius);
background: transparent;
color: white;
border: 2px dashed #3b497a;
cursor: pointer;
transition: background-color 0.3s ease;
}
#modal-panel input[type="file"]:focus,
#modal-panel input[type="file"]:hover {
background-color: #445a9d44;
}
#modal-panel .btns {
margin-top: 22px;
display: flex;
gap: 14px;
justify-content: flex-end;
}
#modal-panel button {
min-width: 90px;
cursor: pointer;
border: none;
border-radius: var(--btn-radius);
font-weight: 700;
color: white;
padding: 10px 0;
font-size: var(--font-size-md);
box-shadow: 0 3px 8px var(--color-shadow-deep);
transition: background-color 0.3s ease;
}
#modal-btn-save {
background-color: #4caf50;
}
#modal-btn-cancel {
background-color: #f44336;
}
#modal-panel button:focus {
outline: 2px solid #76c7ff;
outline-offset: 2px;
}
/* 关闭按钮 */
#modal-close-btn {
position: absolute;
top: 12px;
right: 12px;
background: transparent;
border: none;
color: #bbb;
cursor: pointer;
width: 30px;
height: 30px;
font-size: 24px;
line-height: 30px;
font-weight: 700;
user-select: none;
transition: color 0.25s ease;
}
#modal-close-btn:hover {
color: #fff;
}
/* 搜索结果弹窗 */
#search-result-modal {
position: fixed;
top: 20vh;
left: 50%;
transform: translateX(-50%);
min-width: 320px;
max-width: 80vw;
max-height: 60vh;
background: linear-gradient(135deg, #f0f8ffee, #e3eff8cc);
box-shadow: 0 10px 20px rgb(40 73 138 / 0.5);
border-radius: 16px;
padding: 20px;
opacity: 0;
pointer-events: none;
overflow-y: auto;
user-select: text;
z-index: 1100;
transition: opacity 0.3s ease;
}
#search-result-modal.active {
opacity: 1;
pointer-events: auto;
}
#search-result-modal h3 {
font-weight: 700;
font-size: var(--font-size-lg);
margin-bottom: 12px;
color: #134cb9;
}
#search-result-list {
list-style: none;
}
#search-result-list li {
padding: 8px 10px;
border-bottom: 1px solid #c8d7f7;
cursor: default;
}
#search-result-list li:last-child {
border: none;
}
#search-result-modal .close-btn {
position: absolute;
top: 10px;
right: 10px;
background: transparent;
border: none;
font-size: 22px;
font-weight: 700;
cursor: pointer;
color: #333;
user-select: none;
transition: color 0.25s ease;
}
#search-result-modal .close-btn:hover {
color: #0066ff;
}
/* 输入框与按钮的无障碍聚焦: outline样式 */
input:focus-visible,
button:focus-visible,
select:focus-visible,
textarea:focus-visible {
outline: 2px solid #4285f4;
outline-offset: 2px;
}
/* 上传提示文字 */
.upload-hint {
font-size: 12px;
font-style: italic;
color: #ccc;
}
</style>
</head>
<body>
<div id="app" aria-label="货架货物管理系统">
<!-- 左侧侧边栏 -->
<nav id="sidebar" aria-label="货架列表" role="navigation">
<header id="sidebar-header">
<label id="sidebar-logo-wrapper" for="logo-upload" title="点击上传自定义Logo" tabindex="0" role="button" aria-describedby="logo-upload-desc">
<!-- 默认SVG LOGO -->
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none" stroke="#30445D" stroke-width="4" stroke-linejoin="round" stroke-linecap="round" aria-hidden="true">
<rect x="8" y="8" width="48" height="48" rx="8" ry="8"/>
<line x1="16" y1="32" x2="48" y2="32" />
<line x1="32" y1="16" x2="32" y2="48" />
</svg>
<input type="file" accept="image/*" id="logo-upload" aria-describedby="logo-upload-desc" />
</label>
<h1 id="sidebar-title">仓库管理</h1>
</header>
<section id="shelf-list" role="list" aria-label="货架列表">
<ul id="shelf-ul">
<!-- 货架列表填充 -->
</ul>
</section>
<footer id="sidebar-footer">
<button id="sidebar-toggle-btn" aria-label="切换侧边栏折叠" aria-pressed="false">
<svg id="sidebar-toggle-icon" viewBox="0 0 24 24" stroke="currentColor" fill="none" >
<polyline points="6 9 12 15 18 9" />
</svg>
</button>
</footer>
</nav>
<!-- 右侧主区域 -->
<main id="main-area" role="main">
<!-- 背景层 -->
<div id="background-layer" aria-hidden="true">
<img id="background-image" alt="" draggable="false" />
<canvas id="particle-canvas"></canvas>
</div>
<!-- 工具栏 -->
<section id="toolbar" aria-label="操作工具栏" role="region">
<input
type="search"
id="search-input"
placeholder="搜索货物名称..."
aria-label="全局搜索货物"
autocomplete="off"
/>
<label for="file-import-input" class="operation-btn" tabindex="0" role="button" aria-describedby="import-desc" id="btn-import-label" >导入Excel
<input type="file" id="file-import-input" accept=".xlsx,.xls" aria-describedby="import-desc" />
</label>
<button type="button" id="btn-export" class="operation-btn" aria-label="导出Excel">导出Excel</button>
<button type="button" id="btn-save" class="operation-btn" aria-label="保存当前数据" disabled>保存</button>
</section>
<!-- 货物列表 -->
<section id="goods-table-wrapper" aria-label="货物列表" tabindex="0">
<table id="goods-table" role="grid" aria-readonly="true" aria-multiselectable="true">
<thead>
<tr>
<th scope="col" aria-label="选择"><input type="checkbox" id="select-all" aria-label="全选货物" /></th>
<th scope="col">图片</th>
<th scope="col">品名</th>
<th scope="col">种类</th>
<th scope="col">数量</th>
<th scope="col">金额</th>
</tr>
</thead>
<tbody id="goods-tbody" role="rowgroup">
<!-- 货物数据填充 -->
</tbody>
</table>
</section>
<!-- 操作按钮区 -->
<section id="action-buttons" aria-label="货物操作按钮" role="region">
<button type="button" id="btn-add" aria-label="添加货物">添加</button>
<button type="button" id="btn-edit" aria-label="编辑货物" disabled>编辑</button>
<button type="button" id="btn-delete" aria-label="删除货物" disabled>删除</button>
<button type="button" id="btn-move" aria-label="移动货物" disabled>移动</button>
</section>
</main>
<!-- 添加/编辑货物弹窗 -->
<div id="modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="modal-title" tabindex="-1">
<div id="modal-panel">
<button id="modal-close-btn" aria-label="关闭弹窗" title="关闭弹窗">×</button>
<h2 id="modal-title">添加货物</h2>
<form id="modal-form" novalidate>
<label for="input-name">品名 <span aria-hidden="true">*</span></label>
<input type="text" id="input-name" name="name" placeholder="请输入品名" required autocomplete="off" />
<label for="input-category">种类 <span aria-hidden="true">*</span></label>
<input type="text" id="input-category" name="category" placeholder="请输入种类" required autocomplete="off" />
<label for="input-quantity">数量 <span aria-hidden="true">*</span></label>
<input type="number" min="0" step="1" id="input-quantity" name="quantity" placeholder="输入数量" required autocomplete="off" />
<label for="input-price">金额 (元)</label>
<input type="number" min="0" step="0.01" id="input-price" name="price" placeholder="输入金额" autocomplete="off" />
<label for="input-image">上传图片 (支持PNG/JPG/GIF)</label>
<input type="file" id="input-image" accept="image/png,image/jpeg,image/gif" aria-describedby="upload-image-desc" />
<div id="upload-image-desc" class="upload-hint" aria-live="polite">无图片时显示斜杠占位</div>
<div class="btns">
<button type="submit" id="modal-btn-save">保存</button>
<button type="button" id="modal-btn-cancel">取消</button>
</div>
</form>
</div>
</div>
<!-- 搜索结果弹窗 -->
<aside id="search-result-modal" role="dialog" aria-modal="true" aria-labelledby="search-result-title" tabindex="-1">
<button class="close-btn" aria-label="关闭搜索结果">×</button>
<h3 id="search-result-title">搜索结果</h3>
<ul id="search-result-list" role="list" tabindex="0">
<!-- 搜索结果动态填充 -->
</ul>
</aside>
<!-- 播放点击音效 -->
<audio id="click-sound" src="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAIlYAAESsAAACABAAZGF0YQAAAAA="></audio>
<!-- 空白音频,为了兼容自动播放限制 -->
<script>
(() => {
'use strict';
// ------------- 数据模型 -------------
// localStorage 中存储的键
const STORAGE_KEY = 'warehouse_management_data_v1';
// 货架数据结构示例
/*
{
shelves: [
{
id: 'shelf-uuid',
name: '货架名称',
goods: [
{
id: 'goods-uuid',
name: '货物品名',
category: '分类',
quantity: 10,
price: 100.5,
imageBase64: 'data:image/png;base64,...',
}
]
}
],
logoBase64: 'data:image/png;base64,...',
backgroundBase64: 'data:image/png;base64,...',
}
*/
// ------------- 通用工具 -------------
// 生成唯一ID (简易版UUID v4)
function generateId() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = (Math.random()*16)|0, v = c==='x'? r : (r&0x3|0x8);
return v.toString(16);
});
}
// 检查是否JSON数据有效
function safeParse(json) {
try {
return JSON.parse(json);
} catch {
return null;
}
}
// 延迟(Promise)
const delay = ms => new Promise(r => setTimeout(r, ms));
// ------------- 初始化数据和状态 -------------
let DATA = {
shelves: [],
logoBase64: null,
backgroundBase64: null,
};
let CURRENT_SHELF_ID = null;
let SELECTED_GOODS_IDS = new Set();
let UNSAVED_CHANGES = false;
// DOM元素引用
const dom = {
sidebar: document.getElementById('sidebar'),
shelfUl: document.getElementById('shelf-ul'),
sidebarToggleBtn: document.getElementById('sidebar-toggle-btn'),
sidebarToggleIcon: document.getElementById('sidebar-toggle-icon'),
sidebarToggleBtnLbl: document.getElementById('sidebar-toggle-btn'),
sidebarLogoWrapper: document.getElementById('sidebar-logo-wrapper'),
logoUploadInput: document.getElementById('logo-upload'),
sidebarHeaderTitle: document.getElementById('sidebar-title'),
backgroundLayer: document.getElementById('background-layer'),
backgroundImage: document.getElementById('background-image'),
particleCanvas: document.getElementById('particle-canvas'),
searchInput: document.getElementById('search-input'),
btnImportLabel: document.getElementById('btn-import-label'),
fileImportInput: document.getElementById('file-import-input'),
btnExport: document.getElementById('btn-export'),
btnSave: document.getElementById('btn-save'),
goodsTbody: document.getElementById('goods-tbody'),
selectAllCheckbox: document.getElementById('select-all'),
btnAdd: document.getElementById('btn-add'),
btnEdit: document.getElementById('btn-edit'),
btnDelete: document.getElementById('btn-delete'),
btnMove: document.getElementById('btn-move'),
modalBackdrop: document.getElementById('modal-backdrop'),
modalPanel: document.getElementById('modal-panel'),
modalTitle: document.getElementById('modal-title'),
modalCloseBtn: document.getElementById('modal-close-btn'),
modalForm: document.getElementById('modal-form'),
modalInputName: document.getElementById('input-name'),
modalInputCategory: document.getElementById('input-category'),
modalInputQuantity: document.getElementById('input-quantity'),
modalInputPrice: document.getElementById('input-price'),
modalInputImage: document.getElementById('input-image'),
modalBtnSave: document.getElementById('modal-btn-save'),
modalBtnCancel: document.getElementById('modal-btn-cancel'),
searchResultModal: document.getElementById('search-result-modal'),
searchResultList: document.getElementById('search-result-list'),
searchResultCloseBtn: null, // 延后赋值
clickSound: document.getElementById('click-sound'),
};
// ------------- 波纹动画与音效 -------------
function createRipple(event) {
const button = event.currentTarget;
const rect = button.getBoundingClientRect();
const circle = document.createElement('span');
circle.classList.add('ripple');
const size = Math.max(rect.width, rect.height);
circle.style.width = circle.style.height = size + 'px';
circle.style.left = (event.clientX - rect.left - size / 2) + 'px';
circle.style.top = (event.clientY - rect.top - size / 2) + 'px';
button.appendChild(circle);
circle.addEventListener('animationend', () => circle.remove());
}
function playClickSound() {
// 确保音频能播放(有些浏览器需要用户交互),此处可用空音频增强兼容
dom.clickSound.pause();
dom.clickSound.currentTime = 0;
dom.clickSound.play().catch(() => {/*静默失败处理*/});
}
// 给按钮统一绑定波纹和音效
function bindRippleAndSound(el) {
el.addEventListener('click', e => {
createRipple(e);
playClickSound();
});
}
// ------------ localStorage 操作 --------------
function loadDataFromStorage() {
const raw = localStorage.getItem(STORAGE_KEY);
if(raw) {
const loaded = safeParse(raw);
if(loaded) {
DATA = loaded;
// 保证基本结构
DATA.shelves = Array.isArray(DATA.shelves) ? DATA.shelves : [];
// 自动选择第一个货架(如果存在)
if(DATA.shelves.length > 0) {
CURRENT_SHELF_ID = DATA.shelves[0].id;
} else {
CURRENT_SHELF_ID = null;
}
}
}
}
function saveDataToStorage() {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(DATA));
UNSAVED_CHANGES = false;
updateSaveButtonStatus();
} catch(e) {
alert('保存数据失败!请确保浏览器允许使用localStorage');
}
}
function updateSaveButtonStatus() {
dom.btnSave.disabled = !UNSAVED_CHANGES;
}
// ------------- 侧边栏渲染 -------------
function renderShelves() {
dom.shelfUl.innerHTML = '';
DATA.shelves.forEach(shelf => {
const li = document.createElement('li');
li.setAttribute('role', 'listitem');
li.dataset.id = shelf.id;
const shelfDiv = document.createElement('div');
shelfDiv.className = 'shelf-item';
if(shelf.id === CURRENT_SHELF_ID) {
shelfDiv.classList.add('selected');
}
shelfDiv.tabIndex = 0;
shelfDiv.setAttribute('aria-selected', shelf.id === CURRENT_SHELF_ID ? 'true' : 'false');
shelfDiv.setAttribute('role', 'option');
shelfDiv.setAttribute('aria-label', `货架: ${shelf.name}`);
// 名字显示 (非编辑状态)
const nameSpan = document.createElement('span');
nameSpan.className = 'name';
nameSpan.textContent = shelf.name;
nameSpan.title = shelf.name;
shelfDiv.appendChild(nameSpan);
// 编辑输入框,初始隐藏(以后切换用)
const renameInput = document.createElement('input');
renameInput.type = 'text';
renameInput.className = 'rename-input';
renameInput.value = shelf.name;
renameInput.style.display = 'none';
renameInput.setAttribute('aria-label', '重命名货架名字');
shelfDiv.appendChild(renameInput);
// 操作按钮组
const btnGroup = document.createElement('div');
btnGroup.className = 'shelf-buttons';
// 编辑按钮
const btnEdit = document.createElement('button');
btnEdit.type = 'button';
btnEdit.title = '重命名货架';
btnEdit.className = 'btn-edit-shelf';
btnEdit.setAttribute('aria-label', `编辑货架:${shelf.name}`);
btnEdit.innerHTML = `<svg class="icon-edit" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M12 20h9"></path><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"></path>
</svg>`;
btnGroup.appendChild(btnEdit);
// 删除按钮(只对空货架启用)
const btnDelete = document.createElement('button');
btnDelete.type = 'button';
btnDelete.title = '删除货架(仅空货架可删除)';
btnDelete.className = 'btn-delete-shelf';
btnDelete.setAttribute('aria-label', `删除货架:${shelf.name}`);
btnDelete.disabled = shelf.goods.length > 0;
btnDelete.innerHTML = `<svg class="icon-delete" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<polyline points="3 6 5 6 21 6"></polyline>
<path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"></path>
<path d="M10 11v6"></path>
<path d="M14 11v6"></path>
<path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"></path>
</svg>`;
btnGroup.appendChild(btnDelete);
shelfDiv.appendChild(btnGroup);
li.appendChild(shelfDiv);
dom.shelfUl.appendChild(li);
// 事件绑定
shelfDiv.addEventListener('click', () => {
if(dom.sidebar.classList.contains('collapsed')) return; // 防止点击折叠缩小图标
selectShelfById(shelf.id);
});
shelfDiv.addEventListener('keydown', e => {
if(e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
selectShelfById(shelf.id);
}
});
btnEdit.addEventListener('click', e => {
e.stopPropagation();
startRenameShelf(shelf.id, shelfDiv, nameSpan, renameInput, btnEdit);
});
renameInput.addEventListener('keydown', e => {
if(e.key === 'Enter') {
e.preventDefault();
finishRenameShelf(shelf.id, renameInput.value.trim(), shelfDiv, nameSpan, renameInput, btnEdit);
} else if(e.key === 'Escape') {
cancelRenameShelf(shelfDiv, nameSpan, renameInput, btnEdit);
}
});
renameInput.addEventListener('blur', () => {
finishRenameShelf(shelf.id, renameInput.value.trim(), shelfDiv, nameSpan, renameInput, btnEdit);
});
btnDelete.addEventListener('click', e => {
e.stopPropagation();
if(confirm(`确认删除货架【${shelf.name}】吗?此操作不可恢复。`)) {
deleteShelfById(shelf.id);
}
});
});
}
// 选择货架
function selectShelfById(id, skipFocus=false) {
if(CURRENT_SHELF_ID === id) return;
CURRENT_SHELF_ID = id;
renderShelves();
renderGoodsTable();
SELECTED_GOODS_IDS.clear();
updateGoodsActionButtons();
if(!skipFocus) {
dom.goodsTbody.focus();
}
}
// 删除货架
function deleteShelfById(id) {
const shelfIndex = DATA.shelves.findIndex(s => s.id === id);
if(shelfIndex < 0) return;
DATA.shelves.splice(shelfIndex, 1);
if(id === CURRENT_SHELF_ID) {
CURRENT_SHELF_ID = DATA.shelves.length ? DATA.shelves[0].id : null;
}
UNSAVED_CHANGES = true;
updateSaveButtonStatus();
renderShelves();
renderGoodsTable();
}
// 开始重命名货架
function startRenameShelf(id, shelfDiv, nameSpan, renameInput, editBtn) {
shelfDiv.classList.add('editing');
nameSpan.style.display = 'none';
renameInput.style.display = 'block';
renameInput.focus();
renameInput.select();
editBtn.disabled = true;
}
// 结束重命名货架
function finishRenameShelf(id, newName, shelfDiv, nameSpan, renameInput, editBtn) {
if(!newName) {
renameInput.value = nameSpan.textContent;
} else {
const shelf = DATA.shelves.find(s => s.id === id);
if(shelf) {
shelf.name = newName;
nameSpan.textContent = newName;
UNSAVED_CHANGES = true;
updateSaveButtonStatus();
}
}
shelfDiv.classList.remove('editing');
renameInput.style.display = 'none';
nameSpan.style.display = 'inline';
editBtn.disabled = false;
}
// 取消重命名
function cancelRenameShelf(shelfDiv, nameSpan, renameInput, editBtn) {
renameInput.value = nameSpan.textContent;
shelfDiv.classList.remove('editing');
renameInput.style.display = 'none';
nameSpan.style.display = 'inline';
editBtn.disabled = false;
}
// ------------- 渲染货物列表 -------------
function renderGoodsTable() {
const shelf = DATA.shelves.find(s => s.id === CURRENT_SHELF_ID);
dom.goodsTbody.innerHTML = '';
if(!shelf) return;
shelf.goods.forEach(gd => {
const tr = document.createElement('tr');
tr.setAttribute('role', 'row');
tr.dataset.id = gd.id;
if(SELECTED_GOODS_IDS.has(gd.id)) {
tr.classList.add('selected');
tr.setAttribute('aria-selected', 'true');
} else {
tr.setAttribute('aria-selected', 'false');
}
// 复选框列
const tdCheck = document.createElement('td');
tdCheck.setAttribute('role', 'gridcell');
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.tabIndex = -1;
cb.checked = SELECTED_GOODS_IDS.has(gd.id);
cb.setAttribute('aria-label', `选择货物 ${gd.name}`);
cb.addEventListener('change', e => {
e.stopPropagation();
if(cb.checked) SELECTED_GOODS_IDS.add(gd.id);
else SELECTED_GOODS_IDS.delete(gd.id);
updateGoodsActionButtons();
renderGoodsTable();
});
tdCheck.appendChild(cb);
tr.appendChild(tdCheck);
// 图片列
const tdImage = document.createElement('td');
tdImage.setAttribute('role', 'gridcell');
if(gd.imageBase64) {
const img = document.createElement('img');
img.className = 'thumb';
img.src = gd.imageBase64;
img.alt = `货物【${gd.name}】缩略图`;
img.tabIndex = 0;
img.loading = 'lazy';
img.addEventListener('click', e => {
e.stopPropagation();
openImageLightbox(gd.imageBase64);
});
img.addEventListener('keydown', e => {
if(e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
openImageLightbox(gd.imageBase64);
}
});
tdImage.appendChild(img);
} else {
const placeholder = document.createElement('div');
placeholder.className = 'thumb-placeholder';
placeholder.textContent = '/';
placeholder.title = '无图片';
placeholder.setAttribute('aria-label', '无图片占位');
tdImage.appendChild(placeholder);
}
tr.appendChild(tdImage);
// 品名
const tdName = document.createElement('td');
tdName.setAttribute('role', 'gridcell');
tdName.textContent = gd.name;
tr.appendChild(tdName);
// 种类
const tdCat = document.createElement('td');
tdCat.setAttribute('role', 'gridcell');
tdCat.textContent = gd.category;
tr.appendChild(tdCat);
// 数量
const tdQty = document.createElement('td');
tdQty.setAttribute('role', 'gridcell');
tdQty.textContent = gd.quantity;
tr.appendChild(tdQty);
// 金额
const tdPrice = document.createElement('td');
tdPrice.setAttribute('role', 'gridcell');
tdPrice.textContent = gd.price != null ? gd.price.toFixed(2) : '';
tr.appendChild(tdPrice);
// click选中行复选框切换
tr.addEventListener('click', () => {
const id = gd.id;
if(SELECTED_GOODS_IDS.has(id)) {
SELECTED_GOODS_IDS.delete(id);
} else {
SELECTED_GOODS_IDS.add(id);
}
updateGoodsActionButtons();
renderGoodsTable();
});
tr.addEventListener('keydown', e => {
if(e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
const id = gd.id;
if(SELECTED_GOODS_IDS.has(id)) {
SELECTED_GOODS_IDS.delete(id);
} else {
SELECTED_GOODS_IDS.add(id);
}
updateGoodsActionButtons();
renderGoodsTable();
}
});
dom.goodsTbody.appendChild(tr);
});
dom.selectAllCheckbox.checked = shelf.goods.length > 0 && shelf.goods.length === SELECTED_GOODS_IDS.size;
dom.selectAllCheckbox.indeterminate = SELECTED_GOODS_IDS.size > 0 && SELECTED_GOODS_IDS.size < shelf.goods.length;
}
// 选择全部切换
dom.selectAllCheckbox.addEventListener('change', () => {
const shelf = DATA.shelves.find(s => s.id === CURRENT_SHELF_ID);
if(!shelf) return;
if(dom.selectAllCheckbox.checked) {
shelf.goods.forEach(g => SELECTED_GOODS_IDS.add(g.id));
} else {
SELECTED_GOODS_IDS.clear();
}
updateGoodsActionButtons();
renderGoodsTable();
});
// ------------- 货物操作按钮状态 -------------
function updateGoodsActionButtons() {
const count = SELECTED_GOODS_IDS.size;
dom.btnEdit.disabled = (count !== 1);
dom.btnDelete.disabled = (count === 0);
dom.btnMove.disabled = (count === 0);
}
// ------------- 货架与货物添加编辑 -------------
// 添加货物
dom.btnAdd.addEventListener('click', () => {
if(!CURRENT_SHELF_ID) {
alert('请先添加并选择一个货架。');
return;
}
openGoodsModal('add');
});
// 编辑货物
dom.btnEdit.addEventListener('click', () => {
if(SELECTED_GOODS_IDS.size !== 1) return;
openGoodsModal('edit');
});
// 删除货物
dom.btnDelete.addEventListener('click', () => {
if(SELECTED_GOODS_IDS.size === 0) return;
if(confirm(`确认删除 ${SELECTED_GOODS_IDS.size} 个选中货物吗?此操作不可撤销。`)) {
deleteSelectedGoods();
}
});
// 移动货物
dom.btnMove.addEventListener('click', () => {
if(SELECTED_GOODS_IDS.size === 0) return;
openMoveDialog();
});
// 打开货物添加/编辑弹窗
let modalMode = null; // add or edit
function openGoodsModal(mode) {
modalMode = mode;
dom.modalBackdrop.classList.add('active');
dom.modalPanel.scrollTop = 0;
dom.modalForm.reset();
dom.modalInputImage.value = '';
dom.modalInputImage.removeAttribute('data-base64');
if(mode === 'add') {
dom.modalTitle.textContent = '添加货物';
} else if (mode === 'edit') {
dom.modalTitle.textContent = '编辑货物';
// 填充数据
if(SELECTED_GOODS_IDS.size === 1 && CURRENT_SHELF_ID) {
const shelf = DATA.shelves.find(s => s.id === CURRENT_SHELF_ID);
const id = [...SELECTED_GOODS_IDS][0];
const gd = shelf.goods.find(g => g.id === id);
if(gd) {
dom.modalInputName.value = gd.name;
dom.modalInputCategory.value = gd.category;
dom.modalInputQuantity.value = gd.quantity;
dom.modalInputPrice.value = gd.price != null ? gd.price : '';
if(gd.imageBase64) {
dom.modalInputImage.setAttribute('data-base64', gd.imageBase64);
}
}
}
}
dom.modalInputName.focus();
}
// 关闭弹窗
function closeGoodsModal() {
dom.modalBackdrop.classList.remove('active');
modalMode = null;
dom.modalForm.reset();
dom.modalInputImage.value = '';
dom.modalInputImage.removeAttribute('data-base64');
}
dom.modalCloseBtn.addEventListener('click', closeGoodsModal);
dom.modalBtnCancel.addEventListener('click', closeGoodsModal);
// 弹窗表单提交
dom.modalForm.addEventListener('submit', async e => {
e.preventDefault();
// 数据校验
const name = dom.modalInputName.value.trim();
const category = dom.modalInputCategory.value.trim();
const quantityStr = dom.modalInputQuantity.value.trim();
if(!name) {
alert('品名不能为空');
dom.modalInputName.focus();
return;
}
if(!category) {
alert('种类不能为空');
dom.modalInputCategory.focus();
return;
}
const quantity = parseInt(quantityStr, 10);
if(isNaN(quantity) || quantity < 0) {
alert('数量必须为非负整数');
dom.modalInputQuantity.focus();
return;
}
const priceStr = dom.modalInputPrice.value.trim();
let price = null;
if(priceStr) {
price = parseFloat(priceStr);
if(isNaN(price) || price < 0) {
alert('金额必须为非负数字');
dom.modalInputPrice.focus();
return;
}
}
// 处理图片Base64
const imageBase64Stored = dom.modalInputImage.getAttribute('data-base64');
if(dom.modalInputImage.files.length > 0) {
try {
const base64 = await readFileAsDataURL(dom.modalInputImage.files[0]);
updateGoodsInData(name, category, quantity, price, base64);
} catch(err) {
alert('图片读取失败,请重试');
return;
}
} else {
updateGoodsInData(name, category, quantity, price, imageBase64Stored || null);
}
closeGoodsModal();
renderGoodsTable();
UNSAVED_CHANGES = true;
updateSaveButtonStatus();
});
// 读取文件并转换成Base64
function readFileAsDataURL(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject(new Error('文件读取失败'));
reader.readAsDataURL(file);
});
}
// 新增或编辑货物
function updateGoodsInData(name, category, quantity, price, imageBase64) {
if(!CURRENT_SHELF_ID) return;
const shelf = DATA.shelves.find(s => s.id === CURRENT_SHELF_ID);
if(!shelf) return;
if(modalMode === 'add') {
const newGoods = {
id: generateId(),
name,
category,
quantity,
price,
imageBase64,
};
shelf.goods.push(newGoods);
} else if(modalMode === 'edit') {
const id = [...SELECTED_GOODS_IDS][0];
const gd = shelf.goods.find(g => g.id === id);
if(gd) {
gd.name = name;
gd.category = category;
gd.quantity = quantity;
gd.price = price;
gd.imageBase64 = imageBase64 || null;
}
}
}
// 删除选中货物
function deleteSelectedGoods() {
if(!CURRENT_SHELF_ID) return;
const shelf = DATA.shelves.find(s => s.id === CURRENT_SHELF_ID);
if(!shelf) return;
shelf.goods = shelf.goods.filter(g => !SELECTED_GOODS_IDS.has(g.id));
SELECTED_GOODS_IDS.clear();
renderGoodsTable();
updateGoodsActionButtons();
UNSAVED_CHANGES = true;
updateSaveButtonStatus();
}
// 移动选中货物弹窗简易实现
function openMoveDialog() {
// 选择目标货架
const shelfOptions = DATA.shelves.filter(s => s.id !== CURRENT_SHELF_ID);
if(shelfOptions.length === 0) {
alert('没有其他货架可移动,请先添加货架');
return;
}
const names = shelfOptions.map(s => s.name);
let choiceName = prompt(`请输入要移动到的货架名称,支持模糊匹配:\n${names.join(',')}`);
if(!choiceName) return;
choiceName = choiceName.trim();
// 模糊匹配
const found = shelfOptions.find(s => s.name === choiceName);
if(!found) {
alert('未找到匹配货架,请确认名称输入正确');
return;
}
const fromShelf = DATA.shelves.find(s => s.id === CURRENT_SHELF_ID);
const toShelf = found;
// 移动货物
const movingGoods = fromShelf.goods.filter(g => SELECTED_GOODS_IDS.has(g.id));
toShelf.goods.push(...movingGoods);
fromShelf.goods = fromShelf.goods.filter(g => !SELECTED_GOODS_IDS.has(g.id));
SELECTED_GOODS_IDS.clear();
renderGoodsTable();
updateGoodsActionButtons();
UNSAVED_CHANGES = true;
updateSaveButtonStatus();
alert(`成功移动 ${movingGoods.length} 个货物到货架【${toShelf.name}】`);
}
// ------------- 搜索功能 -------------
dom.searchInput.addEventListener('input', debounce(e => {
doSearch(e.target.value);
}, 300));
// 防抖
function debounce(fn, delay=300) {
let timer = null;
return function(...args) {
if(timer) clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
}
}
function doSearch(keyword) {
keyword = keyword.trim().toLowerCase();
if(!keyword) {
closeSearchResult();
return;
}
const results = [];
DATA.shelves.forEach(shelf => {
shelf.goods.forEach(gd => {
if(gd.name.toLowerCase().includes(keyword)) {
results.push({...gd, shelfName: shelf.name});
}
});
});
if(results.length === 0) {
showSearchResult([]);
} else {
showSearchResult(results);
}
}
function showSearchResult(results) {
dom.searchResultModal.classList.add('active');
dom.searchResultList.innerHTML = '';
if(results.length === 0) {
const li = document.createElement('li');
li.textContent = '无匹配结果';
dom.searchResultList.appendChild(li);
return;
}
results.forEach(gd => {
const li = document.createElement('li');
li.tabIndex = 0;
li.textContent = `【${gd.name}】 (${gd.shelfName}) 种类:${gd.category} 数量:${gd.quantity} 金额:${gd.price != null ? gd.price.toFixed(2) : ''}`;
li.addEventListener('click', () => {
// 选中对应货架并高亮货物
const shelf = DATA.shelves.find(s => s.name === gd.shelfName);
if (!shelf) return;
selectShelfById(shelf.id);
SELECTED_GOODS_IDS.clear();
const shelfCopied = shelf.goods.find(g => g.id === gd.id);
if (shelfCopied) {
SELECTED_GOODS_IDS.add(shelfCopied.id);
renderGoodsTable();
updateGoodsActionButtons();
closeSearchResult();
}
});
li.addEventListener('keydown', e => {
if(e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
li.click();
}
});
dom.searchResultList.appendChild(li);
});
}
dom.searchResultCloseBtn = dom.searchResultModal.querySelector('.close-btn');
dom.searchResultCloseBtn.addEventListener('click', closeSearchResult);
dom.searchResultModal.addEventListener('click', e => {
if(e.target === dom.searchResultModal) closeSearchResult();
});
function closeSearchResult() {
dom.searchResultModal.classList.remove('active');
}
// ESC关闭搜索结果
document.addEventListener('keydown', e => {
if(e.key === 'Escape') {
if(dom.modalBackdrop.classList.contains('active')) closeGoodsModal();
if(dom.searchResultModal.classList.contains('active')) closeSearchResult();
}
});
// ------------- Excel导入导出 -------------
// 由于纯html需求,动态加载SheetJS库(cdn最新版)
let XLSX = null;
function loadSheetJS() {
return new Promise((resolve, reject) => {
if(window.XLSX) {
XLSX = window.XLSX;
resolve();
return;
}
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js';
script.onload = () => {
XLSX = window.XLSX;
resolve();
};
script.onerror = () => reject(new Error('加载SheetJS库失败'));
document.body.appendChild(script);
});
}
// 导入Excel监听
dom.fileImportInput.addEventListener('change', async (e) => {
if(e.target.files.length === 0) return;
const file = e.target.files[0];
try {
if(!XLSX) await loadSheetJS();
const data = await file.arrayBuffer();
const workbook = XLSX.read(data);
// 默认读取第一个sheet
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet, {defval: ''});
if(jsonData.length === 0) {
alert('Excel文件内容为空');
return;
}
// 校验数据格式
// 规定字段: 品名(name), 种类(category), 数量(quantity), 金额(price), 图片Base64(imageBase64)
for(let i=0; i<jsonData.length; i++) {
const row = jsonData[i];
if(!row['品名'] || !row['种类'] || row['数量'] === '') {
alert(`第${i+2}行缺少必填字段(品名/种类/数量)`);
return;
}
if(typeof row['数量'] !== 'number' && isNaN(Number(row['数量']))) {
alert(`第${i+2}行数量字段不是数字`);
return;
}
if(row['金额'] !== '' && isNaN(Number(row['金额']))) {
alert(`第${i+2}行金额字段不是数字`);
return;
}
if(row['图片Base64'] && typeof row['图片Base64'] !== 'string') {
alert(`第${i+2}行图片Base64格式错误`);
return;
}
}
// 提示选择货架
if(DATA.shelves.length === 0) {
alert('请先添加至少一个货架');
return;
}
let shelfName = prompt('请输入导入到的货架名称,支持模糊匹配:\n' + DATA.shelves.map(s=>s.name).join(','));
if(!shelfName) {
alert('未选择货架,导入取消');
return;
}
shelfName = shelfName.trim();
const shelf = DATA.shelves.find(s => s.name === shelfName);
if(!shelf) {
alert('未找到匹配货架,导入取消');
return;
}
// 过滤并加入
jsonData.forEach(r => {
shelf.goods.push({
id: generateId(),
name: r['品名'].toString(),
category: r['种类'].toString(),
quantity: parseInt(r['数量'], 10),
price: r['金额'] !== '' ? parseFloat(r['金额']) : null,
imageBase64: r['图片Base64'] || null
});
});
alert(`成功导入 ${jsonData.length} 条数据到货架【${shelf.name}】`);
UNSAVED_CHANGES = true;
updateSaveButtonStatus();
if(CURRENT_SHELF_ID !== shelf.id) {
selectShelfById(shelf.id);
} else {
renderGoodsTable();
}
} catch(err) {
alert('导入Excel失败:'+ err.message);
} finally {
e.target.value = ''; // 重置文件输入
}
});
// 导出Excel
dom.btnExport.addEventListener('click', async () => {
if(!XLSX) {
try {
await loadSheetJS();
} catch(err) {
alert('加载导出库失败:' + err.message);
return;
}
}
if(DATA.shelves.length === 0) {
alert('无货架,无数据导出');
return;
}
const shelf = DATA.shelves.find(s => s.id === CURRENT_SHELF_ID);
if(!shelf) {
alert('请选择货架导出');
return;
}
if(shelf.goods.length === 0) {
alert('当前货架无货物,无法导出');
return;
}
// 构造表数据
const wsData = shelf.goods.map(g => ({
'品名': g.name,
'种类': g.category,
'数量': g.quantity,
'金额': g.price != null ? g.price : '',
'图片Base64': g.imageBase64 || '',
}));
const ws = XLSX.utils.json_to_sheet(wsData, {skipHeader: false});
// 自定义列宽(自适应)
const maxNameLen = Math.max(...wsData.map(r => r['品名'].length), 6);
const maxCatLen = Math.max(...wsData.map(r => r['种类'].length), 6);
ws['!cols'] = [
{wch: maxNameLen + 4},
{wch: maxCatLen + 4},
{wch: 8},
{wch: 10},
{wch: 64},
];
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, '货物列表');
const date = new Date();
const filename = `货物导出_${date.getFullYear()}${pad2(date.getMonth()+1)}${pad2(date.getDate())}_${pad2(date.getHours())}${pad2(date.getMinutes())}${pad2(date.getSeconds())}.xlsx`;
XLSX.writeFile(wb, filename);
});
function pad2(n) {
return (n<10?'0':'')+n;
}
// ------------- 侧边栏折叠 -------------
dom.sidebarToggleBtn.addEventListener('click', () => {
const collapsed = dom.sidebar.classList.toggle('collapsed');
dom.sidebarToggleBtn.setAttribute('aria-pressed', collapsed ? 'true' : 'false');
});
// ------------- 自定义Logo上传 -------------
dom.logoUploadInput.addEventListener('change', async e => {
if(e.target.files.length === 0) return;
const file = e.target.files[0];
if(!file.type.startsWith('image/')) {
alert('请选择图片文件');
e.target.value = '';
return;
}
try {
const base64 = await readFileAsDataURL(file);
DATA.logoBase64 = base64;
updateSidebarLogo();
UNSAVED_CHANGES = true;
updateSaveButtonStatus();
} catch {
alert('Logo上传失败!');
}
e.target.value = '';
});
dom.sidebarLogoWrapper.addEventListener('keydown', e => {
if(e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
dom.logoUploadInput.click();
}
});
function updateSidebarLogo() {
// 清除默认图标,换成自定义图片
if(!DATA.logoBase64) {
// 复原SVG图标
if(!dom.sidebarLogoWrapper.querySelector('svg')) {
const svg = document.createElementNS('http://www.w3.org/2000/svg','svg');
svg.setAttribute('viewBox', '0 0 64 64');
svg.setAttribute('fill', 'none');
svg.setAttribute('stroke', '#30445D');
svg.setAttribute('stroke-width', '4');
svg.setAttribute('stroke-linejoin', 'round');
svg.setAttribute('stroke-linecap', 'round');
svg.setAttribute('aria-hidden', 'true');
svg.innerHTML = `
<rect x="8" y="8" width="48" height="48" rx="8" ry="8"/>
<line x1="16" y1="32" x2="48" y2="32" />
<line x1="32" y1="16" x2="32" y2="48" />
`;
dom.sidebarLogoWrapper.appendChild(svg);
}
const img = dom.sidebarLogoWrapper.querySelector('img');
if(img) img.remove();
return;
}
let img = dom.sidebarLogoWrapper.querySelector('img');
if(!img) {
img = document.createElement('img');
img.alt = '系统LOGO';
dom.sidebarLogoWrapper.appendChild(img);
}
img.src = DATA.logoBase64;
// 移除SVG图标
const svg = dom.sidebarLogoWrapper.querySelector('svg');
if(svg) svg.remove();
}
// ------------- 自定义背景上传和更换 -------------
// 通过“右下角附带按钮”控制,右下角改成原设计,添加替换和清除按钮
const bgControlBtnContainer = document.createElement('div');
bgControlBtnContainer.setAttribute('role', 'region');
bgControlBtnContainer.ariaLabel = '背景图操作按钮';
bgControlBtnContainer.style.position = 'fixed';
bgControlBtnContainer.style.bottom = '16px';
bgControlBtnContainer.style.right = '16px';
bgControlBtnContainer.style.zIndex = '1000';
bgControlBtnContainer.style.display = 'flex';
bgControlBtnContainer.style.flexDirection = 'column';
bgControlBtnContainer.style.gap = '12px';
// 上传背景按钮
const bgUploadLabel = document.createElement('label');
bgUploadLabel.className = 'operation-btn';
bgUploadLabel.textContent = '更换背景';
bgUploadLabel.style.padding = '8px 12px';
bgUploadLabel.style.minWidth = '120px';
bgUploadLabel.tabIndex = 0;
bgUploadLabel.setAttribute('role', 'button');
bgUploadLabel.setAttribute('aria-label', '上传并更换大背景图片');
const bgFileInput = document.createElement('input');
bgFileInput.type = 'file';
bgFileInput.accept = 'image/*';
bgFileInput.style.display = 'none';
bgFileInput.setAttribute('aria-describedby', 'background-upload-desc');
bgUploadLabel.appendChild(bgFileInput);
const bgUploadHint = document.createElement('div');
bgUploadHint.id = 'background-upload-desc';
bgUploadHint.className = 'upload-hint';
bgUploadHint.textContent = '支持PNG、JPG等图片格式,文件尺寸建议不超过2MB';
bgUploadHint.style.fontSize = '11px';
bgUploadHint.style.color = '#405E9BDD';
// 清除背景按钮
const bgClearBtn = document.createElement('button');
bgClearBtn.type = 'button';
bgClearBtn.textContent = '清除背景';
bgClearBtn.className = 'operation-btn';
bgClearBtn.style.minWidth = '120px';
bgControlBtnContainer.appendChild(bgUploadLabel);
bgControlBtnContainer.appendChild(bgUploadHint);
bgControlBtnContainer.appendChild(bgClearBtn);
document.body.appendChild(bgControlBtnContainer);
bgUploadLabel.addEventListener('keydown', e => {
if(e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
bgFileInput.click();
}
});
bgFileInput.addEventListener('change', async e => {
if(e.target.files.length === 0) return;
const file = e.target.files[0];
if(!file.type.startsWith('image/')) {
alert('请选择图片文件');
e.target.value = '';
return;
}
try {
const base64 = await readFileAsDataURL(file);
DATA.backgroundBase64 = base64;
updateBackgroundImage();
UNSAVED_CHANGES = true;
updateSaveButtonStatus();
} catch {
alert('背景上传失败!');
}
e.target.value = '';
});
bgClearBtn.addEventListener('click', () => {
if(confirm('确认清除当前大背景图片吗?')) {
DATA.backgroundBase64 = null;
updateBackgroundImage();
UNSAVED_CHANGES = true;
updateSaveButtonStatus();
}
});
function updateBackgroundImage() {
if(DATA.backgroundBase64) {
dom.backgroundImage.src = DATA.backgroundBase64;
dom.backgroundImage.style.display = 'block';
} else {
dom.backgroundImage.src = '';
dom.backgroundImage.style.display = 'none';
}
}
// ------------- 页面关闭前保存提示 -------------
window.addEventListener('beforeunload', e => {
if(UNSAVED_CHANGES) {
e.preventDefault();
e.returnValue = '';
}
});
// ------------- 按钮绑定波纹和音效 -------------
[
dom.btnAdd,
dom.btnEdit,
dom.btnDelete,
dom.btnMove,
dom.btnExport,
dom.btnSave,
dom.sidebarToggleBtn,
dom.searchResultCloseBtn,
dom.modalBtnCancel,
dom.modalCloseBtn,
bgUploadLabel,
bgClearBtn,
].forEach(bindRippleAndSound);
// 侧边栏内编辑和删除按钮也波纹
// 延迟绑定,待渲染
function bindShelfButtonsRipple() {
dom.shelfUl.querySelectorAll('.btn-edit-shelf, .btn-delete-shelf').forEach(btn => {
bindRippleAndSound(btn);
});
}
// ------------- 网状粒子背景动画 -------------
const canvas = dom.particleCanvas;
const ctx = canvas.getContext('2d');
let width, height;
const PARTICLE_COUNT = 48;
const particles = [];
function setupCanvas() {
width = canvas.clientWidth;
height = canvas.clientHeight;
canvas.width = width * devicePixelRatio;
canvas.height = height * devicePixelRatio;
ctx.scale(devicePixelRatio, devicePixelRatio);
}
function createParticles() {
particles.length = 0;
for(let i=0; i<PARTICLE_COUNT; i++) {
particles.push({
x: Math.random() * width,
y: Math.random() * height,
vx: (Math.random()-0.5)*0.2,
vy: (Math.random()-0.5)*0.2,
r: 1.3 + Math.random() * 0.7,
});
}
}
// 计算距离
function dist(a, b) {
const dx = a.x - b.x;
const dy = a.y - b.y;
return Math.sqrt(dx*dx+dy*dy);
}
function draw() {
ctx.clearRect(0, 0, width, height);
// 线条连接粒子
for(let i=0; i<PARTICLE_COUNT; i++) {
for(let j=i+1; j<PARTICLE_COUNT; j++) {
let d = dist(particles[i], particles[j]);
if(d < 120) {
const alpha = 0.3*(1 - d/120);
ctx.strokeStyle = `rgba(118, 157, 255, ${alpha.toFixed(3)})`;
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(particles[i].x, particles[i].y);
ctx.lineTo(particles[j].x, particles[j].y);
ctx.stroke();
}
}
}
// 绘制粒子
particles.forEach(p => {
ctx.beginPath();
ctx.fillStyle = 'rgba(118, 157, 255, 0.7)';
ctx.shadowColor = 'rgba(118, 157, 255, 0.4)';
ctx.shadowBlur = 8;
ctx.arc(p.x, p.y, p.r, 0, Math.PI*2);
ctx.fill();
ctx.shadowBlur = 0;
});
}
let mouse = {x:-1,y:-1};
function update() {
// 轨迹更新
for(let p of particles) {
p.x += p.vx;
p.y += p.vy;
// 边界反弹
if(p.x < 0 || p.x > width) p.vx = -p.vx;
if(p.y < 0 || p.y > height) p.vy = -p.vy;
// 轻微受鼠标吸引
if(mouse.x>=0 && mouse.y>=0) {
const dx = mouse.x - p.x;
const dy = mouse.y - p.y;
const distMouse = Math.sqrt(dx*dx+dy*dy);
if(distMouse > 0 && distMouse < 100) {
const force = (100 - distMouse)/100 * 0.1;
p.vx += force * dx / distMouse;
p.vy += force * dy / distMouse;
}
}
// 趋势衰减
p.vx *= 0.95;
p.vy *= 0.95;
}
}
function loop() {
update();
draw();
requestAnimationFrame(loop);
}
// 初始化动画
function initParticleAnimation(){
setupCanvas();
createParticles();
loop();
}
// 鼠标移动更新mouse
dom.backgroundLayer.addEventListener('mousemove', e => {
const rect = dom.backgroundLayer.getBoundingClientRect();
mouse.x = e.clientX - rect.left;
mouse.y = e.clientY - rect.top;
});
dom.backgroundLayer.addEventListener('mouseleave', e => {
mouse.x = -1;
mouse.y = -1;
});
// ------------- 图片大图查看 -------------
let lightbox = null;
function openImageLightbox(src) {
if(lightbox) {
lightbox.src = src;
return;
}
lightbox = document.createElement('div');
lightbox.style.position = 'fixed';
lightbox.style.inset = 0;
lightbox.style.background = 'rgba(0,0,0,0.85)';
lightbox.style.display = 'flex';
lightbox.style.alignItems = 'center';
lightbox.style.justifyContent = 'center';
lightbox.style.zIndex = '1200';
lightbox.style.cursor = 'zoom-out';
lightbox.tabIndex = 0;
const img = document.createElement('img');
img.src = src;
img.alt = '货物大图';
img.style.maxWidth = '90vw';
img.style.maxHeight = '90vh';
img.style.borderRadius = '12px';
img.style.boxShadow = '0 16px 48px rgba(0,0,0,0.8)';
lightbox.appendChild(img);
document.body.appendChild(lightbox);
function close() {
if(lightbox) {
lightbox.remove();
lightbox = null;
}
}
lightbox.addEventListener('click', close);
lightbox.addEventListener('keydown', e => {
if(e.key === 'Escape' || e.key === 'Enter' || e.key === ' ') {
close();
}
});
lightbox.focus();
}
// ------------- 程序入口 -------------
function init() {
loadDataFromStorage();
if(DATA.shelves.length === 0) {
// 初始化默认货架
DATA.shelves.push({id: generateId(), name: '默认货架1', goods: []});
CURRENT_SHELF_ID = DATA.shelves[0].id;
}
renderShelves();
renderGoodsTable();
updateGoodsActionButtons();
updateSidebarLogo();
updateBackgroundImage();
updateSaveButtonStatus();
bindShelfButtonsRipple();
initParticleAnimation();
// 保存按钮事件
dom.btnSave.addEventListener('click', () => {
if(UNSAVED_CHANGES) {
saveDataToStorage();
alert('数据已保存!');
}
});
}
init();
})();
</script>
</body>
</html>