996 lines
50 KiB
JavaScript
996 lines
50 KiB
JavaScript
// ==UserScript==
|
||
// @name Mysteel 钢铁价格提取器
|
||
// @namespace solitude@hraulein.com
|
||
// @version 0.8.8
|
||
// @description 实现列表页与详情页的抓取逻辑,统一透视表导出csv/xlsx,支持多维筛选及本地缓存
|
||
// @author ali
|
||
// @match *://*.mysteel.com/market/*
|
||
// @match *://*.mysteel.com/m/*
|
||
// @grant none
|
||
// @require https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js
|
||
// @downloadURL https://gitea.hraulein.com/ali/UserScript/raw/branch/main/MysteelGetMinPrice.js
|
||
// @updateURL https://gitea.hraulein.com/ali/UserScript/raw/branch/main/MysteelGetMinPrice.js
|
||
// ==/UserScript==
|
||
|
||
(function () {
|
||
'use strict';
|
||
|
||
// 判断当前页面类型
|
||
const isListPage = window.location.href.includes('/market/');
|
||
const isDetailPage = window.location.href.includes('/m/');
|
||
|
||
// 预设筛选常量
|
||
let FILTER_OPTIONS = {
|
||
names: ["盘螺", "螺纹钢", "高线"],
|
||
specs: ["Φ6", "Φ8-10", "Φ8", "Φ10", "Φ12", "Φ14", "Φ16", "Φ18", "Φ20", "Φ22", "Φ25", "Φ28", "Φ32", "Φ36-40", "Φ36", "Φ40"],
|
||
materials: ["HPB300", "HRB400", "HRB400E", "HRB500E"]
|
||
};
|
||
|
||
// 尝试加载本地存储的动态筛选项目
|
||
try {
|
||
const dynamicOpts = localStorage.getItem('mysteel_dynamic_options');
|
||
if (dynamicOpts) {
|
||
Object.assign(FILTER_OPTIONS, JSON.parse(dynamicOpts));
|
||
}
|
||
} catch (e) { }
|
||
|
||
// ==========================================
|
||
// 状态守卫区
|
||
// ==========================================
|
||
|
||
// 校验登录状态
|
||
function isUserLoggedIn() {
|
||
// 未登录时页面存在带有 'topbar-nav-login' 类的元素
|
||
const loginElement = document.querySelector('.topbar-nav-login');
|
||
if (loginElement) {
|
||
return false; // 存在“登录”按钮,说明未登录
|
||
}
|
||
return true; // 已登录
|
||
}
|
||
|
||
// 读取本地缓存的筛选条件
|
||
function loadSavedFilters() {
|
||
const defaultFilters = { names: [], specs: [], materials: [], excludes: '', exportFormat: 'xlsx', exportFilename: '钢材透视价格表', debugMode: false, devMode: false, groupMerge: true };
|
||
const saved = localStorage.getItem('mysteel_filters');
|
||
if (saved) {
|
||
try {
|
||
return { ...defaultFilters, ...JSON.parse(saved) };
|
||
} catch (e) {
|
||
console.error('解析缓存筛选条件失败', e);
|
||
}
|
||
}
|
||
return defaultFilters;
|
||
}
|
||
|
||
// 保存筛选条件到本地缓存
|
||
function saveFiltersToLocal(filters) {
|
||
localStorage.setItem('mysteel_filters', JSON.stringify(filters));
|
||
}
|
||
|
||
function getCurrentFilters() {
|
||
const formatEl = document.getElementById('ms-filter-format');
|
||
const filenameEl = document.getElementById('ms-filter-filename');
|
||
const excludesEl = document.getElementById('ms-filter-excludes');
|
||
const debugModeEl = document.getElementById('ms-debug-mode');
|
||
const devModeEl = document.getElementById('ms-dev-mode-switch');
|
||
const groupMergeEl = document.getElementById('ms-filter-group-merge');
|
||
return {
|
||
names: Array.from(document.querySelectorAll('input[name="ms-filter-names"]:checked')).map(el => el.value),
|
||
specs: Array.from(document.querySelectorAll('input[name="ms-filter-specs"]:checked')).map(el => el.value),
|
||
materials: Array.from(document.querySelectorAll('input[name="ms-filter-materials"]:checked')).map(el => el.value),
|
||
excludes: excludesEl ? excludesEl.value : '',
|
||
exportFormat: formatEl ? formatEl.value : 'csv',
|
||
exportFilename: filenameEl ? filenameEl.value : '钢材透视价格表',
|
||
devMode: devModeEl ? devModeEl.checked : false,
|
||
debugMode: (devModeEl && devModeEl.checked && debugModeEl) ? debugModeEl.checked : false,
|
||
groupMerge: groupMergeEl ? groupMergeEl.checked : true
|
||
};
|
||
}
|
||
|
||
// ==========================================
|
||
// 构建交互 UI
|
||
// ==========================================
|
||
function injectUI() {
|
||
if (document.getElementById('mysteel-tool-container')) return;
|
||
|
||
const savedFilters = loadSavedFilters();
|
||
|
||
const container = document.createElement('div');
|
||
container.id = 'mysteel-tool-container';
|
||
Object.assign(container.style, {
|
||
position: 'fixed', bottom: '50px', right: '50px',
|
||
display: 'flex', alignItems: 'flex-end', gap: '10px',
|
||
zIndex: '99999', fontFamily: 'sans-serif'
|
||
});
|
||
|
||
// --- 主按钮 ---
|
||
const btn = document.createElement('button');
|
||
btn.id = 'mysteel-action-btn';
|
||
// 根据页面类型设定按钮文字
|
||
btn.innerText = isListPage ? '🚀 批量提取数据' : '📊 提取当日数据';
|
||
|
||
Object.assign(btn.style, {
|
||
padding: '12px 24px',
|
||
backgroundColor: isListPage ? '#fa541c' : '#1890ff',
|
||
color: '#fff',
|
||
border: 'none', borderRadius: '6px', fontSize: '16px', fontWeight: 'bold',
|
||
boxShadow: '0 4px 12px rgba(0,0,0,0.2)', cursor: 'pointer', transition: '0.3s'
|
||
});
|
||
|
||
btn.onmouseover = () => btn.style.backgroundColor = isListPage ? '#ff7875' : '#40a9ff';
|
||
btn.onmouseout = () => btn.style.backgroundColor = isListPage ? '#fa541c' : '#1890ff';
|
||
|
||
// 绑定对应的执行引擎
|
||
if (isListPage) {
|
||
btn.addEventListener('click', startBatchProcess);
|
||
} else if (isDetailPage) {
|
||
btn.addEventListener('click', startSingleProcess);
|
||
}
|
||
|
||
// --- 齿轮图标 ---
|
||
const gearBtn = document.createElement('div');
|
||
gearBtn.innerHTML = '⚙️';
|
||
Object.assign(gearBtn.style, {
|
||
width: '46px', height: '46px', backgroundColor: '#fff',
|
||
borderRadius: '50%', display: 'flex', justifyContent: 'center', alignItems: 'center',
|
||
fontSize: '24px', boxShadow: '0 4px 12px rgba(0,0,0,0.2)', cursor: 'pointer',
|
||
userSelect: 'none'
|
||
});
|
||
|
||
// --- 悬浮状态提示面板 ---
|
||
const tooltip = document.createElement('div');
|
||
Object.assign(tooltip.style, {
|
||
display: 'none', position: 'absolute', bottom: '60px', right: '0',
|
||
backgroundColor: 'rgba(0,0,0,0.85)', color: '#fff', padding: '12px',
|
||
borderRadius: '6px', fontSize: '13px', width: 'max-content',
|
||
maxWidth: '300px', lineHeight: '1.5', pointerEvents: 'none',
|
||
boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
|
||
});
|
||
|
||
// --- 高级筛选配置面板 ---
|
||
const panel = document.createElement('div');
|
||
panel.id = 'mysteel-filter-panel';
|
||
Object.assign(panel.style, {
|
||
display: 'none', position: 'absolute', bottom: '60px', right: '0',
|
||
backgroundColor: '#fff', padding: '20px', borderRadius: '8px',
|
||
boxShadow: '0 4px 24px rgba(0,0,0,0.2)', width: '360px',
|
||
color: '#333', border: '1px solid #eee', maxHeight: '80vh', overflowY: 'auto'
|
||
});
|
||
|
||
// 动态生成带有缓存状态的 Checkbox HTML
|
||
const buildCheckboxes = (groupName, options) => {
|
||
return options.map(opt => {
|
||
const isChecked = savedFilters[groupName].includes(opt) ? 'checked' : '';
|
||
return `
|
||
<label style="display:flex; align-items:center; font-size:13px; cursor:pointer;">
|
||
<input type="checkbox" name="ms-filter-${groupName}" value="${opt}" style="margin-right:4px;" ${isChecked}> ${opt}
|
||
</label>
|
||
`;
|
||
}).join('');
|
||
};
|
||
|
||
panel.innerHTML = `
|
||
<style>
|
||
.ms-switch { position: relative; display: inline-block; width: 34px; height: 20px; }
|
||
.ms-switch input { opacity: 0; width: 0; height: 0; margin: 0; }
|
||
.ms-slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: .4s; border-radius: 34px; }
|
||
.ms-slider:before { position: absolute; content: ""; height: 14px; width: 14px; left: 3px; bottom: 3px; background-color: white; transition: .4s; border-radius: 50%; }
|
||
.ms-switch input:checked + .ms-slider { background-color: #1890ff; }
|
||
.ms-switch input:checked + .ms-slider:before { transform: translateX(14px); }
|
||
.ms-tooltip-btn { position: relative; }
|
||
.ms-tooltip-btn:hover::after { content: attr(data-tooltip); position: absolute; bottom: 120%; left: 50%; transform: translateX(-50%); background-color: rgba(0,0,0,0.8); color: #fff; padding: 4px 8px; border-radius: 4px; font-size: 12px; white-space: nowrap; z-index: 1000; pointer-events: none; }
|
||
.ms-tooltip-btn:hover::before { content: ''; position: absolute; bottom: 100%; left: 50%; transform: translateX(-50%); border-width: 4px; border-style: solid; border-color: rgba(0,0,0,0.8) transparent transparent transparent; z-index: 1000; pointer-events: none; }
|
||
.ms-selectall-switch { position: relative; display: inline-block; width: 26px; height: 14px; margin: 0; }
|
||
.ms-selectall-switch input { opacity: 0; width: 0; height: 0; margin: 0; }
|
||
.ms-selectall-slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: .3s; border-radius: 14px; }
|
||
.ms-selectall-slider:before { position: absolute; content: ""; height: 10px; width: 10px; left: 2px; bottom: 2px; background-color: white; transition: .3s; border-radius: 50%; box-shadow: 0 1px 2px rgba(0,0,0,0.2); }
|
||
.ms-selectall-switch input:checked + .ms-selectall-slider { background-color: #fa541c; }
|
||
.ms-selectall-switch input:checked + .ms-selectall-slider:before { transform: translateX(12px); }
|
||
#mysteel-filter-panel::-webkit-scrollbar { width: 6px; }
|
||
#mysteel-filter-panel::-webkit-scrollbar-thumb { background: #d9d9d9; border-radius: 4px; }
|
||
#mysteel-filter-panel::-webkit-scrollbar-track { background: transparent; }
|
||
</style>
|
||
<div style="font-size:14px; font-weight:bold; margin-bottom:15px; background:#f5f5f5; color:#333; padding:4px 6px; border-radius:4px; border-left:4px solid #1890ff; display:flex; justify-content:space-between; align-items:center;">
|
||
<div style="display:flex; align-items:center; gap:8px;">
|
||
<span>⚙️ 筛选配置</span>
|
||
<button id="ms-extract-options-btn" class="ms-tooltip-btn" data-tooltip="从当前页面获取筛选项目并更新到脚本配置中" style="background:none; border:none; cursor:pointer; color:#1890ff; padding:2px; display:flex; align-items:center; justify-content:center; border-radius:4px; outline:none;">
|
||
<svg viewBox="0 0 24 24" width="13" height="13" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round">
|
||
<polyline points="23 4 23 10 17 10"></polyline>
|
||
<polyline points="1 20 1 14 7 14"></polyline>
|
||
<path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"></path>
|
||
</svg>
|
||
</button>
|
||
</div>
|
||
</div>
|
||
<div id="ms-extract-confirm-box" style="display:none; margin-bottom:15px; padding:10px; background:#e6f7ff; border:1px solid #91d5ff; border-radius:4px;">
|
||
<div style="font-size:12px; color:#1890ff; margin-bottom:8px; line-height:1.4;">确定要从当前页面提取新的筛选参数吗?<br>这将会更新并覆盖现有的配置项目。</div>
|
||
<div style="display:flex; justify-content:flex-end; gap:8px;">
|
||
<button id="ms-extract-cancel-btn" style="background:#f5f5f5; color:#333; border:1px solid #d9d9d9; padding:2px 8px; border-radius:4px; font-size:12px; cursor:pointer; outline:none;">取消</button>
|
||
<button id="ms-extract-confirm-action-btn" style="background:#1890ff; color:#fff; border:none; padding:2px 8px; border-radius:4px; font-size:12px; cursor:pointer; outline:none;">确定</button>
|
||
</div>
|
||
</div>
|
||
<div style="margin-bottom:12px;">
|
||
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px;">
|
||
<div style="font-size:13px; color:#333; font-weight:bold;">类别</div>
|
||
<label class="ms-selectall-switch" title="全选/全不选"><input type="checkbox" id="ms-selectall-names"><span class="ms-selectall-slider"></span></label>
|
||
</div>
|
||
<div id="ms-names-container" style="display:grid; grid-template-columns:repeat(5, 1fr); gap:8px 4px;">${buildCheckboxes('names', FILTER_OPTIONS.names)}</div>
|
||
</div>
|
||
<div style="margin-bottom:12px;">
|
||
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px;">
|
||
<div style="font-size:13px; color:#333; font-weight:bold;">线径</div>
|
||
<label class="ms-selectall-switch" title="全选/全不选"><input type="checkbox" id="ms-selectall-specs"><span class="ms-selectall-slider"></span></label>
|
||
</div>
|
||
<div id="ms-specs-container" style="display:grid; grid-template-columns:repeat(5, 1fr); gap:8px 4px;">${buildCheckboxes('specs', FILTER_OPTIONS.specs)}</div>
|
||
</div>
|
||
<div style="margin-bottom:15px;">
|
||
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px;">
|
||
<div style="font-size:13px; color:#333; font-weight:bold;">材质</div>
|
||
<label class="ms-selectall-switch" title="全选/全不选"><input type="checkbox" id="ms-selectall-materials"><span class="ms-selectall-slider"></span></label>
|
||
</div>
|
||
<div id="ms-materials-container" style="display:grid; grid-template-columns:repeat(4, 1fr); gap:8px 4px;">${buildCheckboxes('materials', FILTER_OPTIONS.materials)}</div>
|
||
<div style="margin-top:12px; border-top:1px dashed #eee; padding-top:12px; display:flex; justify-content:space-between; align-items:center;">
|
||
<div class="ms-tooltip-btn" data-tooltip="(Φ8/10 归为 Φ8-10, Φ36/40 归为 Φ36-40)" style="font-size:13px; color:#333; font-weight:bold; cursor:help;">分组合并取值</div>
|
||
<label class="ms-selectall-switch"><input type="checkbox" id="ms-filter-group-merge" ${savedFilters.groupMerge !== false ? 'checked' : ''}><span class="ms-selectall-slider"></span></label>
|
||
</div>
|
||
</div>
|
||
|
||
<div style="font-size:14px; font-weight:bold; margin-bottom:15px; margin-top:15px; background:#f5f5f5; color:#333; padding:4px 6px; border-radius:4px; border-left:4px solid #1890ff;">🛡️ 排除配置</div>
|
||
<div style="margin-bottom:15px;">
|
||
<textarea id="ms-filter-excludes" placeholder="在此输入不要的数据组合,空格分隔,一行一条。\n例如输入:盘螺 Φ8\n则会精确排除所有线径为Φ8的盘螺,而保留Φ8-10。" style="width:100%; height:88px; padding:6px 8px; font-size:12px; border:1px solid #ccc; border-radius:4px; outline:none; resize:vertical; box-sizing:border-box; line-height:1.5;">${savedFilters.excludes || ''}</textarea>
|
||
</div>
|
||
<div style="font-size:14px; font-weight:bold; margin-bottom:15px; margin-top:15px; background:#f5f5f5; color:#333; padding:4px 6px; border-radius:4px; border-left:4px solid #1890ff;">📤 导出配置</div>
|
||
<div style="margin-bottom:12px; display:flex; gap:10px; align-items:flex-end;">
|
||
<div style="flex:1;">
|
||
<div style="font-size:13px; color:#333; font-weight:bold; margin-bottom:6px;">格式</div>
|
||
<select id="ms-filter-format" style="width:100%; padding:4px 8px; font-size:13px; height:28px; box-sizing:border-box; border:1px solid #ccc; border-radius:4px; outline:none;">
|
||
<option value="xlsx" ${savedFilters.exportFormat === 'xlsx' ? 'selected' : ''}>XLSX</option>
|
||
<option value="csv" ${savedFilters.exportFormat === 'csv' ? 'selected' : ''}>CSV</option>
|
||
</select>
|
||
</div>
|
||
<div style="flex:2;">
|
||
<div style="font-size:13px; color:#333; font-weight:bold; margin-bottom:6px;">文件名</div>
|
||
<input type="text" id="ms-filter-filename" value="${savedFilters.exportFilename || '钢材透视价格表'}" style="width:100%; padding:4px 8px; font-size:13px; height:28px; box-sizing:border-box; border:1px solid #ccc; border-radius:4px; outline:none;">
|
||
</div>
|
||
</div>
|
||
<div style="font-size:14px; font-weight:bold; margin-bottom:15px; margin-top:15px; background:#f5f5f5; color:#333; padding:4px 6px; border-radius:4px; border-left:4px solid #1890ff; display:flex; justify-content:space-between; align-items:center;">
|
||
<span>🛠️ 开发者选项</span>
|
||
<label class="ms-switch">
|
||
<input type="checkbox" id="ms-dev-mode-switch" ${savedFilters.devMode ? 'checked' : ''}>
|
||
<span class="ms-slider"></span>
|
||
</label>
|
||
</div>
|
||
<div id="ms-dev-options-container" style="display:${savedFilters.devMode ? 'block' : 'none'}; margin-bottom:12px;">
|
||
<div style="display:flex; justify-content:flex-start; align-items:center; gap:10px;">
|
||
<input type="checkbox" id="ms-debug-mode" style="display:none;" ${savedFilters.debugMode ? 'checked' : ''}>
|
||
<button id="ms-debug-mode-btn" class="ms-tooltip-btn" data-tooltip="跳过登录限制、账号查询权限及价格拦截直接导出" style="background:${savedFilters.debugMode ? '#ff4d4f' : '#f5f5f5'}; color:${savedFilters.debugMode ? '#fff' : '#999'}; border:1px solid ${savedFilters.debugMode ? '#ff4d4f' : '#d9d9d9'}; padding:4px 8px; border-radius:4px; font-size:12px; cursor:pointer; font-weight:bold; outline:none; transition:.3s;">
|
||
DEBUG_MODE ${savedFilters.debugMode ? 'ON' : 'OFF'}
|
||
</button>
|
||
<button id="ms-reset-options-btn" class="ms-tooltip-btn" data-tooltip="恢复默认配置并清除所有缓存数据" style="background:#ff4d4f; color:#fff; border:none; padding:4px 8px; border-radius:4px; font-size:12px; cursor:pointer; font-weight:bold; outline:none;">RESET</button>
|
||
</div>
|
||
<div id="ms-reset-confirm-box" style="display:none; margin-top:10px; padding:10px; background:#fff2f0; border:1px solid #ffccc7; border-radius:4px;">
|
||
<div style="font-size:12px; color:#ff4d4f; margin-bottom:8px; line-height:1.4;">确定要恢复默认配置吗?<br>这将清除所有保存的配置和提取的筛选参数。</div>
|
||
<div style="display:flex; justify-content:flex-end; gap:8px;">
|
||
<button id="ms-reset-cancel-btn" style="background:#f5f5f5; color:#333; border:1px solid #d9d9d9; padding:2px 8px; border-radius:4px; font-size:12px; cursor:pointer; outline:none;">取消</button>
|
||
<button id="ms-reset-confirm-action-btn" style="background:#ff4d4f; color:#fff; border:none; padding:2px 8px; border-radius:4px; font-size:12px; cursor:pointer; outline:none;">确定</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div style="display:flex; gap:10px; margin-top:15px;">
|
||
<button id="ms-apply-btn" style="flex:1; padding:8px; background:#fff; color:#1890ff; border:1px solid #1890ff; border-radius:4px; cursor:pointer; font-weight:bold; outline:none;">应用</button>
|
||
<button id="ms-save-btn" style="flex:1; padding:8px; background:#1890ff; color:#fff; border:none; border-radius:4px; cursor:pointer; font-weight:bold; outline:none;">保存</button>
|
||
<button id="ms-close-btn" style="flex:1; padding:8px; background:#f5f5f5; color:#333; border:1px solid #d9d9d9; border-radius:4px; cursor:pointer; font-weight:bold; outline:none;">关闭</button>
|
||
</div>
|
||
`;
|
||
|
||
// --- UI 交互逻辑 ---
|
||
gearBtn.addEventListener('mouseenter', () => {
|
||
if (panel.style.display === 'block') return;
|
||
const f = getCurrentFilters();
|
||
const formatF = (arr) => arr.length > 0 ? arr.join(', ') : '全部';
|
||
tooltip.innerHTML = `
|
||
<div style="font-weight:bold; margin-bottom:4px;">当前筛选状态:</div>
|
||
<div>类别:${formatF(f.names)}</div>
|
||
<div>线径:${formatF(f.specs)}</div>
|
||
<div>材质:${formatF(f.materials)}</div>
|
||
<div style="margin-top:4px; border-top:1px solid rgba(255,255,255,0.2); padding-top:4px;">
|
||
格式:${f.exportFormat.toUpperCase()}
|
||
</div>
|
||
`;
|
||
tooltip.style.display = 'block';
|
||
});
|
||
|
||
gearBtn.addEventListener('mouseleave', () => {
|
||
tooltip.style.display = 'none';
|
||
});
|
||
|
||
gearBtn.addEventListener('click', () => {
|
||
tooltip.style.display = 'none';
|
||
if (panel.style.display === 'none') {
|
||
syncUIWithFilters(loadSavedFilters());
|
||
panel.style.display = 'block';
|
||
} else {
|
||
panel.style.display = 'none';
|
||
}
|
||
});
|
||
|
||
// 组装 DOM
|
||
container.appendChild(panel);
|
||
container.appendChild(tooltip);
|
||
container.appendChild(btn);
|
||
container.appendChild(gearBtn);
|
||
document.body.appendChild(container);
|
||
|
||
// 初始化及绑定全选事件
|
||
function updateAllSelectAllStates() {
|
||
['names', 'specs', 'materials'].forEach(group => {
|
||
const selectAllCheckbox = document.getElementById(`ms-selectall-${group}`);
|
||
const container = document.getElementById(`ms-${group}-container`);
|
||
if (selectAllCheckbox && container) {
|
||
const checkboxes = Array.from(container.querySelectorAll(`input[name="ms-filter-${group}"]`));
|
||
const allChecked = checkboxes.length > 0 && checkboxes.every(cb => cb.checked);
|
||
selectAllCheckbox.checked = allChecked;
|
||
}
|
||
});
|
||
}
|
||
|
||
function syncUIWithFilters(filters) {
|
||
['names', 'specs', 'materials'].forEach(group => {
|
||
const container = document.getElementById(`ms-${group}-container`);
|
||
if (container) {
|
||
container.querySelectorAll('input[type="checkbox"]').forEach(cb => {
|
||
cb.checked = filters[group] && filters[group].includes(cb.value);
|
||
});
|
||
}
|
||
});
|
||
const excludesEl = document.getElementById('ms-filter-excludes');
|
||
if (excludesEl) excludesEl.value = filters.excludes || '';
|
||
const groupMergeEl = document.getElementById('ms-filter-group-merge');
|
||
if (groupMergeEl) groupMergeEl.checked = filters.groupMerge !== false;
|
||
const formatEl = document.getElementById('ms-filter-format');
|
||
if (formatEl) formatEl.value = filters.exportFormat || 'xlsx';
|
||
const filenameEl = document.getElementById('ms-filter-filename');
|
||
if (filenameEl) filenameEl.value = filters.exportFilename || '钢材透视价格表';
|
||
|
||
const devModeEl = document.getElementById('ms-dev-mode-switch');
|
||
if (devModeEl) {
|
||
devModeEl.checked = !!filters.devMode;
|
||
const devContainer = document.getElementById('ms-dev-options-container');
|
||
if (devContainer) devContainer.style.display = filters.devMode ? 'block' : 'none';
|
||
}
|
||
const debugModeEl = document.getElementById('ms-debug-mode');
|
||
if (debugModeEl) {
|
||
debugModeEl.checked = !!filters.debugMode;
|
||
const btn = document.getElementById('ms-debug-mode-btn');
|
||
if (btn) {
|
||
if (debugModeEl.checked) {
|
||
btn.style.background = '#ff4d4f';
|
||
btn.style.color = '#fff';
|
||
btn.style.borderColor = '#ff4d4f';
|
||
btn.innerText = 'DEBUG_MODE ON';
|
||
} else {
|
||
btn.style.background = '#f5f5f5';
|
||
btn.style.color = '#999';
|
||
btn.style.borderColor = '#d9d9d9';
|
||
btn.innerText = 'DEBUG_MODE OFF';
|
||
}
|
||
}
|
||
}
|
||
updateAllSelectAllStates();
|
||
}
|
||
|
||
['names', 'specs', 'materials'].forEach(group => {
|
||
const selectAllCheckbox = document.getElementById(`ms-selectall-${group}`);
|
||
const container = document.getElementById(`ms-${group}-container`);
|
||
|
||
// 点击全选时的处理
|
||
selectAllCheckbox.addEventListener('change', (e) => {
|
||
const checkboxes = container.querySelectorAll(`input[name="ms-filter-${group}"]`);
|
||
checkboxes.forEach(cb => cb.checked = e.target.checked);
|
||
});
|
||
|
||
// 监听单个选项的变化以更新全选状态
|
||
container.addEventListener('change', (e) => {
|
||
if (e.target.tagName.toLowerCase() === 'input') {
|
||
updateAllSelectAllStates();
|
||
}
|
||
});
|
||
});
|
||
|
||
// 初始状态同步
|
||
updateAllSelectAllStates();
|
||
|
||
// 绑定开发者模式开关事件
|
||
document.getElementById('ms-dev-mode-switch').addEventListener('change', (e) => {
|
||
const devContainer = document.getElementById('ms-dev-options-container');
|
||
devContainer.style.display = e.target.checked ? 'block' : 'none';
|
||
});
|
||
|
||
// 绑定 DEBUG_MODE 按钮切换事件
|
||
document.getElementById('ms-debug-mode-btn').addEventListener('click', (e) => {
|
||
const checkbox = document.getElementById('ms-debug-mode');
|
||
checkbox.checked = !checkbox.checked;
|
||
const btn = e.target;
|
||
if (checkbox.checked) {
|
||
btn.style.background = '#ff4d4f';
|
||
btn.style.color = '#fff';
|
||
btn.style.borderColor = '#ff4d4f';
|
||
btn.innerText = 'DEBUG_MODE ON';
|
||
} else {
|
||
btn.style.background = '#f5f5f5';
|
||
btn.style.color = '#999';
|
||
btn.style.borderColor = '#d9d9d9';
|
||
btn.innerText = 'DEBUG_MODE OFF';
|
||
}
|
||
});
|
||
|
||
// 绑定更新筛选项目相关事件
|
||
document.getElementById('ms-extract-options-btn').addEventListener('click', () => {
|
||
document.getElementById('ms-extract-confirm-box').style.display = 'block';
|
||
});
|
||
|
||
document.getElementById('ms-extract-cancel-btn').addEventListener('click', () => {
|
||
document.getElementById('ms-extract-confirm-box').style.display = 'none';
|
||
});
|
||
|
||
document.getElementById('ms-extract-confirm-action-btn').addEventListener('click', () => {
|
||
document.getElementById('ms-extract-confirm-box').style.display = 'none';
|
||
const getList = (num) => {
|
||
const ul = document.querySelector(`.table-filter-select[sort-line-num="${num}"] .table-filter-select-dropdown-list`);
|
||
if (!ul) return [];
|
||
return Array.from(ul.querySelectorAll('li')).map(li => li.innerText.trim());
|
||
};
|
||
const extractedNames = getList('1');
|
||
const extractedSpecs = getList('2');
|
||
const extractedMaterials = getList('3');
|
||
|
||
if (extractedNames.length === 0 && extractedSpecs.length === 0 && extractedMaterials.length === 0) {
|
||
showToast('筛选项目提取失败:当前页面未发现相关的筛选列表节点!\n请确认当前详情页或页面结构未改变。', 'error');
|
||
return;
|
||
}
|
||
|
||
// 对提取的数据进行格式化处理 (类别倒序,线径从小到大)
|
||
const sortedNames = extractedNames.reverse();
|
||
const sortedSpecs = extractedSpecs.sort((a, b) => {
|
||
const nA = parseFloat(a.replace('Φ', '').split('-')[0]) || 0;
|
||
const nB = parseFloat(b.replace('Φ', '').split('-')[0]) || 0;
|
||
return nA - nB;
|
||
});
|
||
|
||
// 更新内存与本地缓存
|
||
FILTER_OPTIONS.names = sortedNames;
|
||
FILTER_OPTIONS.specs = sortedSpecs;
|
||
FILTER_OPTIONS.materials = extractedMaterials;
|
||
localStorage.setItem('mysteel_dynamic_options', JSON.stringify({
|
||
names: sortedNames,
|
||
specs: sortedSpecs,
|
||
materials: extractedMaterials
|
||
}));
|
||
|
||
// 更新 DOM 呈现
|
||
document.getElementById('ms-names-container').innerHTML = buildCheckboxes('names', FILTER_OPTIONS.names);
|
||
document.getElementById('ms-specs-container').innerHTML = buildCheckboxes('specs', FILTER_OPTIONS.specs);
|
||
document.getElementById('ms-materials-container').innerHTML = buildCheckboxes('materials', FILTER_OPTIONS.materials);
|
||
|
||
// 更新全选框状态
|
||
updateAllSelectAllStates();
|
||
|
||
const code = ` let FILTER_OPTIONS = {\n names: ${JSON.stringify(sortedNames)},\n specs: ${JSON.stringify(sortedSpecs)},\n materials: ${JSON.stringify(extractedMaterials)}\n };`;
|
||
console.log('【提取并排序后的筛选项目】\\n' + code);
|
||
|
||
if (navigator.clipboard && window.isSecureContext) {
|
||
navigator.clipboard.writeText(code).then(() => {
|
||
showToast('筛选项目更新成功,配置代码已复制到剪贴板,可自行更新到脚本的 FILTER_OPTIONS 变量中', 'success');
|
||
}).catch(() => {
|
||
showToast('筛选项目更新成功,配置代码已复制到剪贴板,请按 F12 前往控制台复制。', 'success');
|
||
});
|
||
} else {
|
||
showToast('筛选项目更新成功,请按 F12 前往控制台复制配置代码。', 'success');
|
||
}
|
||
});
|
||
|
||
// 绑定恢复默认设置相关事件
|
||
document.getElementById('ms-reset-options-btn').addEventListener('click', () => {
|
||
document.getElementById('ms-reset-confirm-box').style.display = 'block';
|
||
});
|
||
|
||
document.getElementById('ms-reset-cancel-btn').addEventListener('click', () => {
|
||
document.getElementById('ms-reset-confirm-box').style.display = 'none';
|
||
});
|
||
|
||
document.getElementById('ms-reset-confirm-action-btn').addEventListener('click', () => {
|
||
localStorage.removeItem('mysteel_filters');
|
||
localStorage.removeItem('mysteel_dynamic_options');
|
||
showToast('恢复默认配置成功!即将刷新页面...', 'success');
|
||
setTimeout(() => window.location.reload(), 1000);
|
||
});
|
||
|
||
// 绑定底部按钮事件
|
||
document.getElementById('ms-apply-btn').addEventListener('click', () => {
|
||
const active = getCurrentFilters();
|
||
saveFiltersToLocal(active);
|
||
showToast('配置已应用', 'success');
|
||
});
|
||
|
||
document.getElementById('ms-save-btn').addEventListener('click', () => {
|
||
const active = getCurrentFilters();
|
||
saveFiltersToLocal(active);
|
||
panel.style.display = 'none';
|
||
showToast('配置已保存', 'success');
|
||
});
|
||
|
||
document.getElementById('ms-close-btn').addEventListener('click', () => {
|
||
panel.style.display = 'none';
|
||
syncUIWithFilters(loadSavedFilters());
|
||
});
|
||
|
||
// 点击外部关闭面板 (不保存)
|
||
document.addEventListener('click', (e) => {
|
||
if (panel.style.display === 'block') {
|
||
if (!panel.contains(e.target) && !gearBtn.contains(e.target) && !tooltip.contains(e.target)) {
|
||
panel.style.display = 'none';
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
// ==========================================
|
||
// 引擎 A: 详情页单页抓取
|
||
// ==========================================
|
||
function startSingleProcess() {
|
||
const filters = getCurrentFilters();
|
||
// 🔒 登录状态守卫拦截
|
||
if (!filters.debugMode && !isUserLoggedIn()) {
|
||
showToast('请登录 Mysteel 账号后重试!', 'error');
|
||
return;
|
||
}
|
||
|
||
const btn = document.getElementById('mysteel-action-btn');
|
||
const originalText = btn.innerText;
|
||
btn.innerText = '正在提取...';
|
||
btn.disabled = true;
|
||
|
||
try {
|
||
// 提取日期:从 <span class="content-info-text publish-time"> 提取
|
||
const dateEl = document.querySelector('.content-info-text.publish-time');
|
||
if (!dateEl) {
|
||
showToast('未找到页面的发布时间,请确认当前网页结构!', 'error');
|
||
return;
|
||
}
|
||
// 提取 "2026-07-24 17:41" 中的 "2026-07-24"
|
||
const dateStr = dateEl.innerText.trim().split(' ')[0];
|
||
|
||
const activeFilters = getCurrentFilters();
|
||
|
||
// 直接读取当前 DOM 树中的数据
|
||
const flatData = extractDataFromDoc(document, dateStr, activeFilters);
|
||
|
||
if (flatData.length > 0) {
|
||
generatePivotExport(flatData, '单日');
|
||
} else {
|
||
showToast('根据当前筛选条件,未提取到有效数据!', 'warning');
|
||
}
|
||
} catch (error) {
|
||
if (error.message === 'NO_PERMISSION') {
|
||
showToast('当前账号暂无权限查看价格数据,请确认是否已购买或开通相关权限!', 'warning');
|
||
} else {
|
||
console.error('详情页提取出错:', error);
|
||
showToast('发生错误,请查看控制台日志。', 'error');
|
||
}
|
||
} finally {
|
||
btn.innerText = originalText;
|
||
btn.disabled = false;
|
||
}
|
||
}
|
||
|
||
// ==========================================
|
||
// 引擎 B: 列表页批量抓取
|
||
// ==========================================
|
||
async function startBatchProcess() {
|
||
const filters = getCurrentFilters();
|
||
// 🔒 登录状态守卫拦截
|
||
if (!filters.debugMode && !isUserLoggedIn()) {
|
||
showToast('请登录 Mysteel 账号后重试!', 'error');
|
||
return;
|
||
}
|
||
|
||
const btn = document.getElementById('mysteel-action-btn');
|
||
const originalText = btn.innerText;
|
||
btn.disabled = true;
|
||
btn.style.backgroundColor = '#ccc';
|
||
|
||
try {
|
||
btn.innerText = '正在分析列表...';
|
||
const targetLinks = getTargetLinks();
|
||
if (targetLinks.length === 0) {
|
||
showToast('未发现符合条件的链接!', 'warning');
|
||
return;
|
||
}
|
||
|
||
let flatData = [];
|
||
const activeFilters = getCurrentFilters();
|
||
|
||
// 顺序加载每一个页面
|
||
for (let i = 0; i < targetLinks.length; i++) {
|
||
const linkObj = targetLinks[i];
|
||
btn.innerText = `正在渲染: ${linkObj.date} (${i + 1}/${targetLinks.length})...`;
|
||
|
||
try {
|
||
const doc = await getRenderedDocViaIframe(linkObj.url);
|
||
if (doc) {
|
||
const dailyData = extractDataFromDoc(doc, linkObj.date, activeFilters);
|
||
if (dailyData.length > 0) {
|
||
flatData = flatData.concat(dailyData);
|
||
}
|
||
} else {
|
||
showToast(`日期 ${linkObj.date} 页面加载失败或因跨域重定向,已跳过`, 'warning');
|
||
}
|
||
} catch (err) {
|
||
if (err.message === 'NO_PERMISSION') throw err;
|
||
console.error(`渲染 ${linkObj.date} 失败:`, err);
|
||
}
|
||
}
|
||
|
||
btn.innerText = '正在生成数据透视表...';
|
||
|
||
if (flatData.length > 0) {
|
||
generatePivotExport(flatData, '批量');
|
||
} else {
|
||
showToast('根据当前筛选条件,未能提取到任何数据!', 'warning');
|
||
}
|
||
|
||
} catch (error) {
|
||
if (error.message === 'NO_PERMISSION') {
|
||
showToast('当前账号暂无权限查看价格数据,请确认是否已购买或开通相关权限!', 'warning');
|
||
} else {
|
||
console.error('批量处理出错:', error);
|
||
showToast('发生错误,请查看控制台。', 'error');
|
||
}
|
||
} finally {
|
||
btn.innerText = originalText;
|
||
btn.disabled = false;
|
||
btn.style.backgroundColor = '#fa541c';
|
||
}
|
||
}
|
||
|
||
// ==========================================
|
||
// 公共组件区
|
||
// ==========================================
|
||
|
||
// Toast 提示组件
|
||
function showToast(message, type = 'info') {
|
||
const toast = document.createElement('div');
|
||
toast.innerText = message;
|
||
|
||
let bgColor = '#1890ff';
|
||
if (type === 'error') bgColor = '#ff4d4f';
|
||
else if (type === 'success') bgColor = '#52c41a';
|
||
else if (type === 'warning') bgColor = '#faad14';
|
||
|
||
Object.assign(toast.style, {
|
||
position: 'fixed',
|
||
top: '30vh',
|
||
left: '50%',
|
||
transform: 'translateX(-50%)',
|
||
backgroundColor: bgColor,
|
||
color: '#fff',
|
||
padding: '12px 24px',
|
||
borderRadius: '4px',
|
||
boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
|
||
zIndex: '999999',
|
||
fontSize: '14px',
|
||
whiteSpace: 'pre-wrap',
|
||
opacity: '0',
|
||
transition: 'opacity 0.3s, top 0.3s',
|
||
pointerEvents: 'none',
|
||
textAlign: 'center',
|
||
lineHeight: '1.5'
|
||
});
|
||
|
||
document.body.appendChild(toast);
|
||
|
||
// 动画显示
|
||
requestAnimationFrame(() => {
|
||
toast.style.opacity = '1';
|
||
toast.style.top = '33vh';
|
||
});
|
||
|
||
// 定时移除
|
||
setTimeout(() => {
|
||
toast.style.opacity = '0';
|
||
toast.style.top = '30vh';
|
||
setTimeout(() => {
|
||
if (toast.parentNode) {
|
||
toast.parentNode.removeChild(toast);
|
||
}
|
||
}, 300);
|
||
}, 5000);
|
||
}
|
||
|
||
// 获取列表页的日期链接
|
||
function getTargetLinks() {
|
||
const listItems = document.querySelectorAll('#articleList .nlist li');
|
||
const dailyMap = new Map();
|
||
|
||
listItems.forEach(li => {
|
||
const dateSpan = li.querySelector('.date');
|
||
const aTag = li.querySelector('a');
|
||
|
||
if (!dateSpan || !aTag) return;
|
||
|
||
const text = aTag.innerText.trim();
|
||
const href = aTag.href;
|
||
|
||
// 过滤掉包含“工程”或“采购”的链接
|
||
if (text.includes('工程') || text.includes('采购')) return;
|
||
|
||
// 过滤早上的行情:要求标题包含时间如 "(17:30)",或者仅提取带有括号的标题
|
||
// 因为早上的标题通常是 "7月29日深圳市场建筑钢材价格行情"
|
||
// 下午的标题通常是 "7月28日(17:30)深圳市场建筑钢材价格行情"
|
||
if (!text.includes('(') && !text.includes('(')) return;
|
||
|
||
const dateTimeStr = dateSpan.innerText.trim();
|
||
const [date, time] = dateTimeStr.split(' ');
|
||
|
||
if (date && time && href.includes('mysteel.com')) {
|
||
// 双重保险:发布时间也必须是下午 (12点之后)
|
||
if (time < '12:00') return;
|
||
|
||
if (!dailyMap.has(date) || time > dailyMap.get(date).time) {
|
||
dailyMap.set(date, { date, time, url: href, title: text });
|
||
}
|
||
}
|
||
});
|
||
|
||
return Array.from(dailyMap.values()).sort((a, b) => b.date.localeCompare(a.date));
|
||
}
|
||
|
||
// Iframe 静默渲染引擎
|
||
async function getRenderedDocViaIframe(url) {
|
||
return new Promise((resolve) => {
|
||
const iframe = document.createElement('iframe');
|
||
Object.assign(iframe.style, {
|
||
width: '0px', height: '0px', visibility: 'hidden', position: 'absolute', border: 'none'
|
||
});
|
||
iframe.src = url;
|
||
|
||
iframe.onload = () => {
|
||
setTimeout(() => {
|
||
try {
|
||
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
|
||
resolve(iframeDoc);
|
||
} catch (e) {
|
||
resolve(null);
|
||
} finally {
|
||
document.body.removeChild(iframe);
|
||
}
|
||
}, 2500);
|
||
};
|
||
|
||
iframe.onerror = () => {
|
||
document.body.removeChild(iframe);
|
||
resolve(null);
|
||
};
|
||
|
||
document.body.appendChild(iframe);
|
||
});
|
||
}
|
||
|
||
// 核心提取与数据清洗过滤引擎
|
||
function extractDataFromDoc(doc, dateStr, filters) {
|
||
const targetTable = doc.getElementById('marketTable');
|
||
if (!targetTable) return [];
|
||
|
||
const tbody = targetTable.querySelector('tbody');
|
||
if (!tbody) return [];
|
||
const rows = tbody.querySelectorAll('tr');
|
||
|
||
const dataMap = new Map();
|
||
|
||
for (let row of rows) {
|
||
if (row.style.display === 'none' || !row.hasAttribute('table-row-id')) continue;
|
||
|
||
const tdBreed = row.querySelector('td[data-type="breed"]');
|
||
const tdSpec = row.querySelector('td[data-type="spec"]');
|
||
const tdMaterial = row.querySelector('td[data-type="material"]');
|
||
const tdPrice = row.querySelector('td[data-type="price"]');
|
||
|
||
if (!tdBreed || !tdSpec || !tdMaterial || !tdPrice) continue;
|
||
|
||
if (tdPrice.querySelector('.icon-key')) {
|
||
if (!filters.debugMode) throw new Error('NO_PERMISSION');
|
||
}
|
||
|
||
const cleanText = (element) => {
|
||
let clone = element.cloneNode(true);
|
||
let childIcons = clone.querySelectorAll('a, img, div');
|
||
childIcons.forEach(icon => icon.remove());
|
||
return clone.innerText.replace(/[\r\n\t]/g, '').trim();
|
||
};
|
||
|
||
const name = cleanText(tdBreed);
|
||
const spec = cleanText(tdSpec);
|
||
const material = cleanText(tdMaterial);
|
||
|
||
// 筛选校验拦截
|
||
if (filters.names.length > 0 && !filters.names.includes(name)) continue;
|
||
if (filters.specs.length > 0 && !filters.specs.includes(spec)) continue;
|
||
if (filters.materials.length > 0 && !filters.materials.includes(material)) continue;
|
||
|
||
// 黑名单精确校验拦截
|
||
if (filters.excludes) {
|
||
const excludeLines = filters.excludes.split('\n').map(l => l.trim()).filter(l => l);
|
||
const currentTokens = [name, spec, material];
|
||
let shouldExclude = false;
|
||
for (let ex of excludeLines) {
|
||
const keywords = ex.split(/\s+/);
|
||
// 确保规则中的每一个词,都在当前行中精确存在
|
||
const matchAll = keywords.every(kw => currentTokens.includes(kw));
|
||
if (matchAll) {
|
||
shouldExclude = true;
|
||
break;
|
||
}
|
||
}
|
||
if (shouldExclude) continue;
|
||
}
|
||
|
||
const priceStr = tdPrice.innerText.replace(/,/g, '').trim();
|
||
let currentPrice = parseFloat(priceStr);
|
||
|
||
if (!name) continue;
|
||
|
||
if (isNaN(currentPrice)) {
|
||
if (!filters.debugMode) continue;
|
||
currentPrice = tdPrice.querySelector('.icon-key') ? '无权限(锁)' : (priceStr || '无数据');
|
||
}
|
||
|
||
// 分组逻辑:在取最低值前,将相关的线径统一归类
|
||
let groupSpec = spec;
|
||
if (filters.groupMerge !== false) {
|
||
if (groupSpec === 'Φ8' || groupSpec === 'Φ10') {
|
||
groupSpec = 'Φ8-10';
|
||
} else if (groupSpec === 'Φ36' || groupSpec === 'Φ40') {
|
||
groupSpec = 'Φ36-40';
|
||
}
|
||
}
|
||
|
||
const uniqueKey = `${name}_${groupSpec}_${material}`;
|
||
|
||
if (!dataMap.has(uniqueKey)) {
|
||
dataMap.set(uniqueKey, {
|
||
date: dateStr,
|
||
name: name,
|
||
spec: groupSpec,
|
||
material: material,
|
||
priceNum: currentPrice
|
||
});
|
||
} else {
|
||
const existing = dataMap.get(uniqueKey);
|
||
if (typeof currentPrice === 'number' && typeof existing.priceNum === 'number') {
|
||
if (currentPrice < existing.priceNum) {
|
||
existing.priceNum = currentPrice;
|
||
}
|
||
} else if (typeof currentPrice === 'number') {
|
||
existing.priceNum = currentPrice;
|
||
}
|
||
}
|
||
}
|
||
return Array.from(dataMap.values());
|
||
}
|
||
|
||
// 数据透视与生成 CSV 或 XLSX
|
||
function generatePivotExport(flatData, filePrefix) {
|
||
// 1. 提取独立日期并升序排列
|
||
const uniqueDates = [...new Set(flatData.map(d => d.date))].sort((a, b) => a.localeCompare(b));
|
||
|
||
// 日期格式化:将 "2026-07-24" 转为 "7/24"
|
||
const formatHeaderDate = (dStr) => {
|
||
const parts = dStr.split('-');
|
||
if (parts.length === 3) {
|
||
return `${parseInt(parts[1], 10)}/${parseInt(parts[2], 10)}`;
|
||
}
|
||
return dStr;
|
||
};
|
||
|
||
const dateHeaders = uniqueDates.map(formatHeaderDate);
|
||
|
||
// 2. 将扁平数据转为透视结构的 Map
|
||
const pivotMap = new Map();
|
||
flatData.forEach(item => {
|
||
const key = `${item.name}_${item.spec}_${item.material}`;
|
||
if (!pivotMap.has(key)) {
|
||
pivotMap.set(key, {
|
||
name: item.name,
|
||
spec: item.spec,
|
||
material: item.material,
|
||
pricesByDate: {}
|
||
});
|
||
}
|
||
pivotMap.get(key).pricesByDate[item.date] = item.priceNum;
|
||
});
|
||
|
||
// 读取导出设置
|
||
const filters = getCurrentFilters();
|
||
const exportFormat = filters.exportFormat || 'csv';
|
||
|
||
// 3. 排序逻辑
|
||
const rows = Array.from(pivotMap.values());
|
||
const nameOrder = {};
|
||
FILTER_OPTIONS.names.forEach((n, i) => nameOrder[n] = i);
|
||
const specOrder = {};
|
||
FILTER_OPTIONS.specs.forEach((s, i) => specOrder[s] = i);
|
||
|
||
rows.sort((a, b) => {
|
||
const nA = nameOrder[a.name] !== undefined ? nameOrder[a.name] : 99;
|
||
const nB = nameOrder[b.name] !== undefined ? nameOrder[b.name] : 99;
|
||
if (nA !== nB) return nA - nB;
|
||
|
||
const sA = specOrder[a.spec] !== undefined ? specOrder[a.spec] : 99;
|
||
const sB = specOrder[b.spec] !== undefined ? specOrder[b.spec] : 99;
|
||
return sA - sB;
|
||
});
|
||
|
||
const exportFilename = filters.exportFilename || '钢材透视价格表';
|
||
const d = new Date();
|
||
const Y = d.getFullYear();
|
||
const M = (d.getMonth() + 1).toString().padStart(2, '0');
|
||
const D = d.getDate().toString().padStart(2, '0');
|
||
const H = d.getHours().toString().padStart(2, '0');
|
||
const m = d.getMinutes().toString().padStart(2, '0');
|
||
const S = d.getSeconds().toString().padStart(2, '0');
|
||
const dateStr = `${Y}${M}${D}${H}${m}${S}`;
|
||
const finalFilename = `${exportFilename}_${filePrefix}_${dateStr}`;
|
||
|
||
if (exportFormat === 'xlsx' && typeof XLSX !== 'undefined') {
|
||
const aoa = [];
|
||
aoa.push(['类别', '线径', '材质', ...dateHeaders]);
|
||
rows.forEach(row => {
|
||
const rowData = [row.name, row.spec, row.material];
|
||
uniqueDates.forEach(date => {
|
||
rowData.push(row.pricesByDate[date] !== undefined ? row.pricesByDate[date] : '');
|
||
});
|
||
aoa.push(rowData);
|
||
});
|
||
const ws = XLSX.utils.aoa_to_sheet(aoa);
|
||
const wb = XLSX.utils.book_new();
|
||
XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
|
||
XLSX.writeFile(wb, `${finalFilename}.xlsx`);
|
||
} else {
|
||
// 4. 拼接 CSV 内容
|
||
let csvContent = '\uFEFF';
|
||
csvContent += `类别,线径,材质,${dateHeaders.join(',')}\n`;
|
||
|
||
rows.forEach(row => {
|
||
let rowText = `"${row.name}","${row.spec}","${row.material}"`;
|
||
uniqueDates.forEach(date => {
|
||
const price = row.pricesByDate[date] !== undefined ? row.pricesByDate[date] : '';
|
||
rowText += `,"${price}"`;
|
||
});
|
||
csvContent += rowText + '\n';
|
||
});
|
||
|
||
// 4. 触发下载
|
||
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
|
||
const url = URL.createObjectURL(blob);
|
||
const link = document.createElement('a');
|
||
|
||
link.setAttribute('href', url);
|
||
link.setAttribute('download', `${finalFilename}.csv`);
|
||
|
||
document.body.appendChild(link);
|
||
link.click();
|
||
|
||
document.body.removeChild(link);
|
||
URL.revokeObjectURL(url);
|
||
}
|
||
|
||
showToast('操作完成,请查看浏览器下载记录!', 'success');
|
||
}
|
||
|
||
// 延时加载注入
|
||
window.addEventListener('load', injectUI);
|
||
setTimeout(injectUI, 2000);
|
||
setTimeout(injectUI, 5000);
|
||
|
||
})(); |