import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react' import type { CompanyProfile, ResearchConversation, ScheduleTask, SearchBatch, SearchConditions, WatchRecord, WatchStatus, } from '../types' import { emptyProfile, demoProfile, HISTORY_STATUSES } from '../types' import { PROJECTS } from '../data/projects' import type { Project } from '../types' // ---------- 本地持久化 ---------- const LS_KEY = 'ruzhou-store-v1' interface Persisted { profile: CompanyProfile watch: WatchRecord[] tasks: ScheduleTask[] research: ResearchConversation[] batches: SearchBatch[] customTags: string[] customProjects: Project[] } /** 旧版状态名 → 新状态名(状态体系细化后的数据迁移) */ const STATUS_MIGRATION: Record = { 已提交: '已提交投标文件', 已结束: '未中标', } const migrateStatus = (s: WatchStatus): WatchStatus => STATUS_MIGRATION[s] ?? s function loadPersisted(): Persisted { try { const raw = localStorage.getItem(LS_KEY) if (raw) { const parsed = JSON.parse(raw) const savedProfile = { ...emptyProfile, ...parsed.profile } return { // 从未填写过档案时载入演示档案,便于直接演示匹配度打分;填过则尊重用户数据 profile: savedProfile.companyName.trim() ? savedProfile : { ...demoProfile }, watch: (parsed.watch ?? []).map((w: WatchRecord) => ({ ...w, tags: w.tags ?? [], status: migrateStatus(w.status), history: (w.history ?? []).map(h => ({ ...h, status: migrateStatus(h.status) })), })), tasks: parsed.tasks ?? [], research: parsed.research ?? [], batches: parsed.batches ?? [], customTags: parsed.customTags ?? [], customProjects: parsed.customProjects ?? [], } } } catch { /* ignore */ } return { profile: { ...demoProfile }, watch: [], tasks: [], research: [], batches: [], customTags: [], customProjects: [] } } export function nowStr(): string { const d = new Date() const p = (n: number) => String(n).padStart(2, '0') return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}` } export function uid(prefix: string): string { return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}` } // ---------- 检索逻辑(严格按用户条件执行,不做二次过滤/重排) ---------- export function runSearch(conditions: SearchConditions): string[] { const kw = conditions.keyword.trim().toLowerCase() const region = conditions.region.trim() const min = conditions.budgetMin.trim() === '' ? null : Number(conditions.budgetMin) const max = conditions.budgetMax.trim() === '' ? null : Number(conditions.budgetMax) const now = new Date() const rangeDays = conditions.publishRange === '7d' ? 7 : conditions.publishRange === '30d' ? 30 : conditions.publishRange === '90d' ? 90 : null return PROJECTS.filter(p => { if (kw) { const hay = [p.name, p.purchaser, p.region, ...p.keywords].join(' ').toLowerCase() // 多个关键词用空格分隔,需全部命中 const terms = kw.split(/\s+/) if (!terms.every(t => hay.includes(t))) return false } if (region && !p.region.includes(region)) return false if (min !== null || max !== null) { // 预算条件仅在用户明确设置时生效;未披露预算的项目无法判断,按不命中处理 if (p.budget === null) return false if (min !== null && p.budget < min) return false if (max !== null && p.budget > max) return false } if (rangeDays !== null) { const pub = new Date(p.publishDate) if ((now.getTime() - pub.getTime()) / 86400000 > rangeDays) return false } return true }).map(p => p.id) } export function conditionsText(c: SearchConditions): string { const parts: string[] = [] if (c.keyword.trim()) parts.push(`关键词「${c.keyword.trim()}」`) if (c.region.trim()) parts.push(`地区「${c.region.trim()}」`) if (c.budgetMin.trim() || c.budgetMax.trim()) { parts.push(`预算 ${c.budgetMin.trim() || '不限'} ~ ${c.budgetMax.trim() || '不限'} 万元`) } const rangeMap = { '7d': '近 7 天', '30d': '近 30 天', '90d': '近 90 天', all: '全部时间' } parts.push(`发布于${rangeMap[c.publishRange]}`) return parts.join(' · ') } // ---------- Context ---------- interface Store { profile: CompanyProfile saveProfile: (p: CompanyProfile) => void watch: WatchRecord[] addWatch: (projectId: string) => void removeWatch: (projectId: string) => void setWatchStatus: (projectId: string, status: WatchStatus) => void setWatchNote: (projectId: string, note: string) => void isWatched: (projectId: string) => boolean toggleWatchTag: (projectId: string, tag: string) => void customTags: string[] addCustomTag: (tag: string) => void removeCustomTag: (tag: string) => void customProjects: Project[] addCustomProject: (p: Project) => void findProject: (id: string) => Project | undefined tasks: ScheduleTask[] saveTask: (t: ScheduleTask) => void deleteTask: (id: string) => void runTaskNow: (id: string) => void research: ResearchConversation[] saveConversation: (c: ResearchConversation) => void deleteConversation: (id: string) => void batches: SearchBatch[] addBatch: (b: SearchBatch) => void } const StoreContext = createContext(null) export function StoreProvider({ children }: { children: React.ReactNode }) { const [state, setState] = useState(loadPersisted) useEffect(() => { try { localStorage.setItem(LS_KEY, JSON.stringify(state)) } catch { /* ignore */ } }, [state]) const saveProfile = useCallback((p: CompanyProfile) => { setState(s => ({ ...s, profile: { ...p, version: s.profile.version + 1, updatedAt: nowStr() }, })) }, []) const addWatch = useCallback((projectId: string) => { setState(s => { // 同一个项目只保留一条关注记录,不因重复来源产生多条 if (s.watch.some(w => w.projectId === projectId)) return s const rec: WatchRecord = { projectId, status: '已关注', note: '', tags: [], createdAt: nowStr(), history: [{ status: '已关注', time: nowStr(), note: '' }], } return { ...s, watch: [rec, ...s.watch] } }) }, []) const removeWatch = useCallback((projectId: string) => { setState(s => ({ ...s, watch: s.watch.filter(w => w.projectId !== projectId) })) }, []) const setWatchStatus = useCallback((projectId: string, status: WatchStatus) => { setState(s => ({ ...s, watch: s.watch.map(w => w.projectId === projectId && w.status !== status ? { ...w, status, history: [...w.history, { status, time: nowStr(), note: w.note }] } : w), })) }, []) const setWatchNote = useCallback((projectId: string, note: string) => { setState(s => ({ ...s, watch: s.watch.map(w => w.projectId === projectId ? { ...w, note } : w) })) }, []) const toggleWatchTag = useCallback((projectId: string, tag: string) => { setState(s => ({ ...s, watch: s.watch.map(w => { if (w.projectId !== projectId) return w const has = w.tags.includes(tag) return { ...w, tags: has ? w.tags.filter(t => t !== tag) : [...w.tags, tag] } }), })) }, []) const addCustomTag = useCallback((tag: string) => { setState(s => s.customTags.includes(tag) ? s : { ...s, customTags: [...s.customTags, tag] }) }, []) const removeCustomTag = useCallback((tag: string) => { setState(s => ({ ...s, customTags: s.customTags.filter(t => t !== tag), // 删除标签时同步从各项目上去掉,避免残留失效标签 watch: s.watch.map(w => w.tags.includes(tag) ? { ...w, tags: w.tags.filter(t => t !== tag) } : w), })) }, []) const addCustomProject = useCallback((p: Project) => { setState(s => { if (s.customProjects.some(x => x.id === p.id) || PROJECTS.some(x => x.id === p.id)) return s const rec: WatchRecord = { projectId: p.id, status: '已关注', note: '', tags: [], createdAt: nowStr(), history: [{ status: '已关注', time: nowStr(), note: '' }], } const watch = s.watch.some(w => w.projectId === p.id) ? s.watch : [rec, ...s.watch] return { ...s, customProjects: [p, ...s.customProjects], watch } }) }, []) const saveTask = useCallback((t: ScheduleTask) => { setState(s => { const idx = s.tasks.findIndex(x => x.id === t.id) if (idx >= 0) { // 编辑不覆盖过去运行记录 const next = [...s.tasks] next[idx] = { ...t, runs: s.tasks[idx].runs } return { ...s, tasks: next } } return { ...s, tasks: [...s.tasks, t] } }) }, []) const deleteTask = useCallback((id: string) => { setState(s => ({ ...s, tasks: s.tasks.filter(t => t.id !== id) })) }, []) const runTaskNow = useCallback((id: string) => { setState(s => ({ ...s, tasks: s.tasks.map(t => { if (t.id !== id) return t const ids = runSearch(t.conditions) return { ...t, runs: [{ time: nowStr(), status: 'success' as const, count: ids.length }, ...t.runs] } }), })) }, []) const saveConversation = useCallback((c: ResearchConversation) => { setState(s => { const idx = s.research.findIndex(x => x.id === c.id) if (idx >= 0) { const next = [...s.research] next[idx] = c return { ...s, research: next } } return { ...s, research: [c, ...s.research] } }) }, []) const deleteConversation = useCallback((id: string) => { setState(s => ({ ...s, research: s.research.filter(c => c.id !== id) })) }, []) const addBatch = useCallback((b: SearchBatch) => { setState(s => ({ ...s, batches: [b, ...s.batches].slice(0, 30) })) }, []) const value = useMemo(() => ({ profile: state.profile, saveProfile, watch: state.watch, addWatch, removeWatch, setWatchStatus, setWatchNote, isWatched: (pid: string) => state.watch.some(w => w.projectId === pid), toggleWatchTag, customTags: state.customTags, addCustomTag, removeCustomTag, customProjects: state.customProjects, addCustomProject, findProject: (id: string) => state.customProjects.find(p => p.id === id) ?? PROJECTS.find(p => p.id === id), tasks: state.tasks, saveTask, deleteTask, runTaskNow, research: state.research, saveConversation, deleteConversation, batches: state.batches, addBatch, }), [state, saveProfile, addWatch, removeWatch, setWatchStatus, setWatchNote, toggleWatchTag, addCustomTag, removeCustomTag, addCustomProject, saveTask, deleteTask, runTaskNow, saveConversation, deleteConversation, addBatch]) return {children} } export function useStore(): Store { const ctx = useContext(StoreContext) if (!ctx) throw new Error('useStore must be used within StoreProvider') return ctx } export function isHistoryStatus(s: WatchStatus): boolean { return (HISTORY_STATUSES as string[]).includes(s) }