import React, { useState, useEffect } from 'react' import { APP_VERSION } from '../config/version' export default function List() { const [collections, setCollections] = useState([]) const [loading, setLoading] = useState(true) const [filter, setFilter] = useState('') const [filterType, setFilterType] = useState('') const urlParams = new URLSearchParams(window.location.hash.split('?')[1] || '') const urlUserId = urlParams.get('userId') || '' const [userIdFilter, setUserIdFilter] = useState(urlUserId) const [sortField, setSortField] = useState('createdAt') const [sortOrder, setSortOrder] = useState('desc') const [viewMode, setViewMode] = useState('list') const [key, setKey] = useState(0) const [search, setSearch] = useState('') const [isAdmin, setIsAdmin] = useState(false) const [page, setPage] = useState(1) const [pagination, setPagination] = useState({ total: 0, pages: 1 }) useEffect(() => { // 检查是否管理员 const userStr = localStorage.getItem('user') if (userStr) { try { const user = JSON.parse(userStr) setIsAdmin(user.role === 'admin') } catch (e) {} } // 监听hash变化,重新读取筛选参数 const handleHashChange = () => { const params = new URLSearchParams(window.location.hash.split('?')[1] || '') // 支持两种格式:filter=category&value=自持 或 filter=category=自持 let filterTypeParam = params.get('filter') || '' let valueParam = params.get('value') || '' if (filterTypeParam && valueParam) { // 新格式:filter=category&value=自持 setFilterType(filterTypeParam) setFilter(decodeURIComponent(valueParam)) } else if (filterTypeParam && filterTypeParam.includes('=')) { // 旧格式:filter=category=自持 const [type, value] = filterTypeParam.split('=') setFilterType(type) setFilter(decodeURIComponent(value)) } else { setFilter('') setFilterType('') } fetchCollections() } handleHashChange() window.addEventListener('hashchange', handleHashChange) window.addEventListener('focus', fetchCollections) return () => { window.removeEventListener('hashchange', handleHashChange) window.removeEventListener('focus', fetchCollections) } }, []) const fetchCollections = async () => { setLoading(true) const token = localStorage.getItem('token') try { // 从URL获取筛选参数 const params = new URLSearchParams(window.location.hash.split('?')[1] || '') const urlFilterType = params.get('filter') || '' const urlFilterValue = params.get('value') ? decodeURIComponent(params.get('value')) : '' let api = '/api/collections?page=' + page + '&limit=100&sortBy=' + sortField + '&sortOrder=' + sortOrder if (urlFilterType && urlFilterValue) { api += '&' + urlFilterType + '=' + encodeURIComponent(urlFilterValue) } const res = await fetch(api, { headers: token ? { 'Authorization': 'Bearer ' + token } : {} }) // 处理 401 未授权错误 if (res.status === 401) { localStorage.removeItem('token') localStorage.removeItem('user') window.location.hash = '#/login' return } const data = await res.json() // 新格式直接返回数组或 {data: [], pagination: {}} let list = data.data || data if (!Array.isArray(list) && list && Array.isArray(list.items)) { list = list.items } // 应用筛选条件 // 用户ID筛选(从URL获取) if (userIdFilter) { list = list.filter(item => item.userId === userIdFilter || item.userId === userIdFilter.replace(/-/g, '')) } if (filterType && filter) { const fieldMap = { status: 'status', category: 'category', packaging: 'packaging', rarity: 'rarity', numberCategory: 'numberCategory', version: 'version', gradingCompany: 'gradingCompany', gradingScore: 'gradingScore', specialMark: 'specialMark', profitLoss: 'profitLoss' } const field = fieldMap[filterType] || filterType if (filterType === 'profitLoss') { // 盈亏筛选:需要计算出售价和总成本 list = list.filter(item => { if (item.status !== 'sold') return false // 只筛选已售 const totalCost = (item.costPrice || 0) + (item.repairFee || 0) + (item.gradingFee || 0) const isProfit = item.goalPrice > totalCost return filter === 'profit' ? isProfit : !isProfit }) } else { list = list.filter(item => { const value = item[field] || item[filterType] return value === filter }) } console.log(`筛选:${filterType} = ${filter}, 结果:${list.length}条`) } setCollections(list || []) // 获取分页信息 if (data.pagination) { setPagination({ total: data.pagination.total || 0, pages: data.pagination.pages || 1 }) } } catch (e) { console.error('Fetch collections error:', e) // 网络错误也跳转到登录页 localStorage.removeItem('token') localStorage.removeItem('user') window.location.hash = '#/login' } setLoading(false) } // 监听页码变化,重新获取数据 useEffect(() => { if (page > 1) { fetchCollections() } }, [page]) const refresh = () => { setKey(k => k + 1) } useEffect(() => { window.refreshList = refresh return () => { delete window.refreshList } }, []) const goDetail = (id) => { // 保存当前列表的URL(包含筛选条件),用于返回时恢复 sessionStorage.setItem('lastListUrl', window.location.hash.substring(1)) window.location.hash = '#/detail?id=' + id } // 获取筛选字段的中文标签 const getFilterLabel = (type) => { const labels = { status: '状态', category: '持仓类型', packaging: '包装', rarity: '珍惜度', version: '版别', gradingCompany: '评级公司', gradingScore: '评级分数', specialMark: '特殊标识', profitLoss: '盈亏' } return labels[type] || type } // 获取筛选条件值的中文显示 const getFilterValueLabel = (type, value) => { const valueLabels = { status: { in_collection: '收藏中', selling: '出售中', sold: '已售', grading: '送评中', repairing: '修复中', transit: '在途中', seeking: '寻号中', other: '其他' }, category: { 自持: '自持', 寄存: '寄存', 寄售: '寄售', 共有: '共有', 寻号: '寻号', 其他: '其他' }, packaging: { 标十: '标十', 标百: '标百', 单张: '单张', 裸钞: '裸钞' }, rarity: { 通货: '通货', 特色: '特色', 少见: '少见', 稀有: '稀有', 珍品: '珍品', 孤品: '孤品' }, profitLoss: { profit: '盈利', loss: '亏损' }, isGraded: { true: '已评级', false: '未评级' } } const typeLabels = valueLabels[type] if (typeLabels) { return typeLabels[value] || value } return value } const versions = collections && collections.length ? [...new Set(collections.map(c => c.version).filter(v => v))] : [] // 筛选和排序 const filteredCollections = collections.filter(c => { // 筛选条件 if (filter && filterType) { if (filterType === 'profitLoss') { if (c.status !== 'sold') return false if (filter === 'profit') return c.goalPrice > c.costPrice return c.goalPrice <= c.costPrice } else if (filterType === 'isGraded') { if (c.isGraded !== (filter === 'true')) return false } else if (c[filterType] !== filter) { return false } } // 搜索 - 全字段搜索 if (search) { const s = search.toLowerCase().trim() // 收集所有可搜索字段 const allFields = [ // 基本信息 c.name, c.code, c.prefixSerial, c.version, c.status, c.category, c.packaging, c.rarity, // 评级信息 c.gradingCompany, c.gradingScore, c.specialMark, c.isGraded ? '已评级' : '未评级', c.threeStar ? '三星' : '', // 价格信息 c.targetPrice?.toString(), c.costPrice?.toString(), c.goalPrice?.toString(), c.repairFee?.toString(), c.gradingFee?.toString(), // 其他 c.remark, c.purpose, c.material, c.denomination, c.issueYear, c.issueQuantity, c.serialFeature, c.issuer, // 用户信息 c.username || '', c.userId || '' ].filter(v => v !== undefined && v !== null).map(v => v.toString().toLowerCase()) if (!allFields.some(f => f.includes(s))) { return false } } return true }).sort((a, b) => { let aVal = a[sortField] let bVal = b[sortField] if (sortField === 'createdAt') { aVal = new Date(a.createdAt || 0).getTime() bVal = new Date(b.createdAt || 0).getTime() } else if (sortField === 'code') { // 编号按数字排序,提取数字部分 aVal = parseInt(a.code?.replace(/\D/g, '') || '0', 10) bVal = parseInt(b.code?.replace(/\D/g, '') || '0', 10) } else if (sortField === 'prefixSerial') { // 冠字号按字母排序 aVal = a.prefixSerial || '' bVal = b.prefixSerial || '' } else if (['costPrice', 'targetPrice', 'goalPrice', 'gradingScore'].includes(sortField)) { // 价格和分数按数字排序 aVal = parseFloat(aVal) || 0 bVal = parseFloat(bVal) || 0 } else if (sortField === 'rarity') { // 珍惜度按等级排序 const rarityOrder = { '通货': 1, '特色': 2, '少见': 3, '稀有': 4, '珍品': 5, '孤品': 6 } aVal = rarityOrder[aVal] || 0 bVal = rarityOrder[bVal] || 0 } else if (sortField === 'numberCategory') { // 号码分类按自定义顺序排序 const numberCategoryOrder = { '无2347': 1, '无347': 2, '无247': 3, '无47': 4, '无4': 5, '带4': 6, '其他': 7 } aVal = numberCategoryOrder[aVal] || 99 bVal = numberCategoryOrder[bVal] || 99 } if (aVal == null) return 1 if (bVal == null) return -1 if (sortOrder === 'asc') { return aVal > bVal ? 1 : -1 } return aVal < bVal ? 1 : -1 }) const clearFilter = () => { setFilter('') setFilterType('') window.location.hash = '#/stats' } const getStatusText = (status) => { const map = { 'in_collection': '收藏中', 'selling': '出售中', 'sold': '已售', 'grading': '送评中', 'repairing': '修复中', 'transit': '在途中', 'seeking': '寻号中', 'other': '其他' } return map[status] || status || '-' } const getCategoryText = (category) => { const map = { '自持': '自持', '寄存': '寄存', '寄售': '寄售', '共有': '共有', '其他': '其他' } return map[category] || category || '自持' } const getCategoryColor = (category) => { const colors = { '自持': '#22c55e', '寄存': '#3b82f6', '寄售': '#f59e0b', '共有': '#8b5cf6', '其他': '#64748b' } return colors[category] || '#64748b' } const getNumberCategoryColor = (cat) => { const colors = { '无2347': '#8b5cf6', '无347': '#ef4444', '无247': '#fbbf24', '无47': '#3b82f6', '无4': '#06b6d4', '带4': '#22c55e', '其他': '#64748b' }; return colors[cat] || '#64748b'; }; const getRarityColor = (rarity) => { const colors = { '通货': '#22c55e', '特色': '#06b6d4', '少见': '#3b82f6', '稀有': '#ec4899', '珍品': '#ef4444', '孤品': '#8b5cf6' } return colors[rarity] || '#64748b' } const formatPrefixSerial = (serial) => { if (!serial) return '-' // 提取J开头的10位(1位J + 9位数字) const match = serial.match(/J(\d{9})/) if (match) return 'J' + match[1] // 如果没有J开头,取前10位 return serial.substring(0, 10) } const getPackagingColor = (packaging) => { const colors = { '裸钞': '#22c55e', '单张': '#3b82f6', '标十': '#fbbf24', '标百': '#8b5cf6' } return colors[packaging] || '#64748b' } const getStatusColor = (status) => { const colors = { 'in_collection': '#22c55e', 'selling': '#f59e0b', 'sold': '#ef4444', 'grading': '#8b5cf6', 'repairing': '#f97316', 'transit': '#06b6d4', 'seeking': '#ec4899', 'other': '#64748b' } return colors[status] || '#64748b' } const getVersionColor = (version) => { if (!version) return { bg: 'rgba(255,255,255,0.08)', color: '#94a3b8' } const v = version.toLowerCase() if (v.includes('龙')) return { bg: 'linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%)', color: '#1e293b' } if (v.includes('蛇')) return { bg: 'linear-gradient(135deg, #ec4899 0%, #db2777 100%)', color: '#fff' } if (v.includes('马')) return { bg: 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)', color: '#fff' } if (v.includes('羊')) return { bg: 'linear-gradient(135deg, #f97316 0%, #ea580c 100%)', color: '#fff' } if (v.includes('猴')) return { bg: 'linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%)', color: '#fff' } if (v.includes('鸡')) return { bg: 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)', color: '#1e293b' } if (v.includes('狗')) return { bg: 'linear-gradient(135deg, #6366f1 0%, #4f46e5 100%)', color: '#fff' } if (v.includes('猪')) return { bg: 'linear-gradient(135deg, #ec4899 0%, #be185d 100%)', color: '#fff' } if (v.includes('鼠')) return { bg: 'linear-gradient(135deg, #64748b 0%, #475569 100%)', color: '#fff' } if (v.includes('牛')) return { bg: 'linear-gradient(135deg, #22c55e 0%, #16a34a 100%)', color: '#fff' } if (v.includes('虎')) return { bg: 'linear-gradient(135deg, #f97316 0%, #ea580c 100%)', color: '#fff' } if (v.includes('兔')) return { bg: 'linear-gradient(135deg, #f43f5e 0%, #e11d48 100%)', color: '#fff' } return { bg: 'linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%)', color: '#1e293b' } } const ListItem = ({ item }) => (