import { useEffect, useMemo, useRef, useState } from 'react' import { useNavigate } from 'react-router' import { Search, Sparkles, Building2, ChevronLeft, ChevronRight, ExternalLink, Star, ArrowRight, Layers, SlidersHorizontal, X, } from 'lucide-react' import { motion, AnimatePresence } from 'framer-motion' import type { AiPanelState, MatchWeights, Project, ScheduleTask, SearchConditions } from '../types' import { RESULT_STATUSES } from '../types' import { useStore, runSearch, conditionsText, uid, nowStr } from '../lib/store' import { BEE_IMG } from '../lib/assets' import { matchScore, timeDigest, keyRequirement } from '../lib/ai' import { ScheduleTasks } from '../components/ScheduleTasks' import { PrimaryButton, GhostButton } from '../components/ui-ext/AiButton' import { cn } from '@/lib/utils' const PAGE_SIZE = 8 const defaultConditions: SearchConditions = { keyword: '', region: '', budgetMin: '', budgetMax: '', publishRange: '30d' } const inputCls = 'rounded-ctrl border border-line-soft bg-white px-3 py-2 text-sm text-ink-900 outline-none transition-shadow placeholder:text-ink-400 focus:border-brand-500/60 focus:ring-2 focus:ring-brand-500/10' const WEIGHT_FIELDS = ['business', 'region', 'amount', 'track'] as const /** 匹配度维度:名称固定,不开放自定义 */ const DIM_NAMES: Record<(typeof WEIGHT_FIELDS)[number], string> = { business: '业务贴合', region: '服务地区', amount: '金额匹配', track: '业绩与资质', } export function DiscoverPage({ onOpenPanel }: { onOpenPanel: (s: AiPanelState) => void }) { const { profile, saveProfile, addBatch, tasks, watch, findProject } = useStore() const navigate = useNavigate() const [conditions, setConditions] = useState(defaultConditions) const [executed, setExecuted] = useState(null) const [resultIds, setResultIds] = useState(null) const [showSchedule, setShowSchedule] = useState(false) const [showWeights, setShowWeights] = useState(false) const [weightDraft, setWeightDraft] = useState(profile.matchWeights) const doSearch = () => { const ids = runSearch(conditions) // 档案已完善时,结果按匹配度由高到低排序 if (profile.completed) { ids.sort((a, b) => (matchScore(findProject(b)!, profile)?.score ?? -1) - (matchScore(findProject(a)!, profile)?.score ?? -1)) } const batch = { id: uid('batch'), conditions: { ...conditions }, executedAt: nowStr(), projectIds: ids, total: ids.length } addBatch(batch) setExecuted({ ...conditions }) setResultIds(ids) } const total = resultIds?.length ?? 0 const dirty = executed !== null && JSON.stringify(conditions) !== JSON.stringify(executed) // 有执行记录的检索方案:结果用与手动检索一致的整表展示,多方案可切换 const ranTasks = useMemo( () => tasks.filter(t => t.runs.length > 0) .sort((a, b) => (b.runs[0]?.time ?? '').localeCompare(a.runs[0]?.time ?? '')), [tasks], ) const watchPreview = useMemo( () => watch.map(w => findProject(w.projectId)).filter(Boolean).slice(0, 6) as Project[], [watch, findProject], ) // 顶部问候条:按时段问候 + 日期 + 临近报名截止的关注项目数 const hour = new Date().getHours() const greeting = hour < 6 ? '夜深了' : hour < 9 ? '早上好' : hour < 12 ? '上午好' : hour < 14 ? '中午好' : hour < 18 ? '下午好' : '晚上好' const today = new Date() const dateStr = `${today.getMonth() + 1}月${today.getDate()}日 星期${'日一二三四五六'[today.getDay()]}` const dueSoon = useMemo(() => { const now = Date.now() return watch.filter(w => { const p = findProject(w.projectId) if (!p?.regDeadline) return false const t = new Date(p.regDeadline).getTime() return t >= now && t - now <= 7 * 86400000 }).length }, [watch, findProject]) // 问候条动态:不做数据罗列,直接给判断——优先提示各方案结果里的高匹配项目; // 未配置方案时展示关注与结果进度 const insight = useMemo(() => { const hits = ranTasks .map(t => ({ name: t.name, count: runSearch(t.conditions) .filter(id => (matchScore(findProject(id)!, profile)?.score ?? 0) >= 90).length, })) .filter(h => h.count > 0) if (hits.length > 0) { return ( <> {hits.map((h, i) => ( {i > 0 && '、'}「{h.name}」有 {h.count} 个 ))} {' '}匹配度超过 90 分的项目,建议优先查看 ) } if (ranTasks.length > 0) { return <>各检索方案暂无 90 分以上的高匹配项目,可在结果区切换标签查看明细 } if (tasks.length > 0) { return <>已保存 {tasks.length} 个检索方案,执行后这里会提示高匹配项目 } const resultCount = watch.filter(w => (RESULT_STATUSES as string[]).includes(w.status)).length return ( <> 重点关注 {watch.length} 个项目, {dueSoon} 个临近报名截止, 已有结果 {resultCount} 个 ) }, [ranTasks, tasks.length, watch, dueSoon, profile, findProject]) return (
{/* 档案已完善:顶部问候条(小巧思:GIF 小助手 + 一句话关键动态) */} {profile.completed && (
{/* 装饰圆环与光斑,与品牌视觉一致 */}
如昼小助手

{greeting},{profile.companyName.replace(/(有限责任公司|有限公司)$/, '') || '朋友'}

{dateStr}

AI 洞察

{insight}

)} {/* 公司档案:仅在未完善时展示引导栏;已完善则不再占位 */} {!profile.completed && (

让 AI 像投标专员一样帮你筛项目

花 2 分钟填好资质、代表业绩和常做区域,之后每条项目都会自动给出贴合度打分和「先看哪条」的建议——不用再一条条读公告。

navigate('/profile')}> 立即完善档案
)} {/* 检索区 */}

项目检索

{ setWeightDraft({ ...profile.matchWeights }) setShowWeights(true) }} className="!px-3 !py-1.5 text-xs"> 匹配度权重 setShowSchedule(true)} className="!px-3 !py-1.5 text-xs"> 检索方案
setConditions(c => ({ ...c, keyword: e.target.value }))} onKeyDown={e => { if (e.key === 'Enter') doSearch() }} placeholder="关键词(空格分隔多个,如:智慧水务 监测)" className={cn(inputCls, 'col-span-4')} /> setConditions(c => ({ ...c, region: e.target.value }))} onKeyDown={e => { if (e.key === 'Enter') doSearch() }} placeholder="地区(如:浙江)" className={cn(inputCls, 'col-span-2')} />
setConditions(c => ({ ...c, budgetMin: e.target.value }))} placeholder="预算下限" className={cn(inputCls, 'w-full font-num')} /> ~ setConditions(c => ({ ...c, budgetMax: e.target.value }))} placeholder="上限(万元)" className={cn(inputCls, 'w-full font-num')} />
检索
{dirty && (
检索条件已修改但尚未重新执行,下方结果仍对应上一次执行的条件({conditionsText(executed!)})。
)}
{/* 检索方案:方案列表收进弹窗,不在首页占位 */} setShowSchedule(false)} /> {/* 结果区:设置了检索方案时,结果区以标签页呈现(当前检索 + 各方案结果),随时切换 */} {ranTasks.length > 0 ? ( ) : resultIds === null ? ( watchPreview.length > 0 ? (

你重点关注的项目

共 {watch.length} 条,展示前 {watchPreview.length} 条 在上方设置条件点击「检索」,发现更多商机
    {watchPreview.map(p => )}
) : (

设置检索条件后点击「检索」

结果按匹配度由高到低排列,点击任意一行查看 AI 分析

) ) : total === 0 ? (

没有符合条件的项目

可调整关键词、地区、预算或发布时间范围后重新检索(系统不会自动放宽你的条件)

) : ( <>

全部结果

共 {total} 条 {conditionsText(executed!)}{profile.completed ? ' · 按匹配度由高到低排序' : ''}
{/* 与检索方案结果共用同一张结果表格 */}
)} {/* 匹配度权重配置 */} {showWeights && ( { if (e.target === e.currentTarget) setShowWeights(false) }}>

匹配度权重

拖动滑块调整各维度权重;合计不为 100 时按比例折算。

{WEIGHT_FIELDS.map(k => (
{DIM_NAMES[k]} setWeightDraft(d => ({ ...d, [k]: Number(e.target.value) }))} className="flex-1 accent-brand-500" /> {weightDraft[k]}%
))}
{(() => { const sum = weightDraft.business + weightDraft.region + weightDraft.amount + weightDraft.track return sum !== 100 ? (

当前合计 {sum}%,保存后按比例折算为 100% 参与计分

) : null })()}
setShowWeights(false)}>取消 { saveProfile({ ...profile, matchWeights: weightDraft, matchDimNames: { ...DIM_NAMES } }) setShowWeights(false) }}>保存权重
)}
) } /** 结果表格:手动检索与检索方案结果共用(含匹配度悬停说明与分页) */ function ResultTable({ ids, onOpenPanel }: { ids: string[]; onOpenPanel: (s: AiPanelState) => void }) { const { profile, findProject, addWatch, isWatched, watch, customTags, addCustomTag, toggleWatchTag } = useStore() const [page, setPage] = useState(1) // 关注后就地打标签的小弹窗:不用切到「重点关注」页再补标签 const [tagPickerFor, setTagPickerFor] = useState(null) const [newTag, setNewTag] = useState('') const submitNewTag = (pid: string) => { const t = newTag.trim() if (!t) return addCustomTag(t) const w = watch.find(x => x.projectId === pid) if (!w?.tags.includes(t)) toggleWatchTag(pid, t) setNewTag('') } const total = ids.length const pageCount = Math.max(1, Math.ceil(total / PAGE_SIZE)) const safePage = Math.min(page, pageCount) const pageIds = useMemo(() => ids.slice((safePage - 1) * PAGE_SIZE, safePage * PAGE_SIZE), [ids, safePage]) return ( <>
{pageIds.map((id, rowIdx) => { const p = findProject(id)! const m = matchScore(p, profile) const t = timeDigest(p) const k = keyRequirement(p) const toneCls = { urgent: 'text-bad-500', warn: 'text-warn-500', ok: 'text-ok-500', muted: 'text-ink-400' }[t.tone] const dotCls = { urgent: 'bg-bad-500', warn: 'bg-warn-500', ok: 'bg-ok-500', muted: 'bg-ink-400' }[t.tone] const kTone = { block: 'bg-bad-500/10 text-bad-500', note: 'bg-[rgba(245,158,11,.1)] text-warn-500', ok: 'bg-ok-500/10 text-ok-500', }[k.tone] return ( onOpenPanel({ kind: 'project', projectId: p.id })} title="点击查看该项目的 AI 深入分析" className="cursor-pointer border-b border-line-soft/70 transition-colors last:border-0 hover:bg-brand-50/40"> ) })}
项目名称 招标方 预算 时间节奏 参与门槛 匹配度 操作
{/* 项目名称直达招标源网页(新标签页打开,保留检索进度) */} e.stopPropagation()} className="inline-flex items-start gap-1 font-medium text-ink-900 hover:text-brand-500 hover:underline"> {p.name}
{p.keywords.slice(0, 2).map(kw => ( {kw} ))}
{p.purchaser}
{p.region}
{p.budget === null ? 未披露 : {p.budget.toLocaleString()} 万元}
{t.label}
{t.sub}
{k.label} {m ? (
{m.score} 分 {/* 悬停展示打分维度与权重;完整报告在该行的「AI 分析」中 */}
= pageIds.length - 3 ? 'bottom-full mb-1' : 'top-full mt-1', )}>
贴合度打分构成 (辅助参考,不参与筛选排序)
    {m.dims.map(d => (
  • {d.name} 权重 {d.weight}% {d.score} 分
    {d.note}
  • ))}
点击本行「AI 分析」查看完整打分报告
) : ( — )}
{/* 关注后的标签弹窗:选择已有标签或新建,不用切页 */} {tagPickerFor === p.id && ( <>
{ e.stopPropagation(); setTagPickerFor(null) }} />
e.stopPropagation()} className={cn('absolute right-0 z-30 w-60 whitespace-normal rounded-card border border-line-soft bg-white p-3 text-left shadow-card-hover', rowIdx >= pageIds.length - 2 ? 'bottom-full mb-1' : 'top-full mt-1')}>
给这个项目打个标签
{customTags.length > 0 && (
{customTags.map(tag => { const on = watch.find(x => x.projectId === p.id)?.tags.includes(tag) ?? false return ( ) })}
)}
setNewTag(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') submitNewTag(p.id) }} placeholder="新建标签,回车添加" className="w-full rounded-ctrl border border-line-soft px-2.5 py-1.5 text-[12px] outline-none placeholder:text-ink-400 focus:border-brand-500/60" />
)}
{/* 分页:说明当前展示范围,不把当前页当作全部 */}
第 {(safePage - 1) * PAGE_SIZE + 1}–{Math.min(safePage * PAGE_SIZE, total)} 条,共 {total} 条 setPage(p => Math.max(1, p - 1))} disabled={safePage <= 1} className="!px-2.5 !py-1 text-xs"> 上一页 第 {safePage} / {pageCount} 页 setPage(p => Math.min(pageCount, p + 1))} disabled={safePage >= pageCount} className="!px-2.5 !py-1 text-xs"> 下一页
) } /** 结果区(有检索方案时):标签页切换「当前检索」与各方案结果,全部共用同一张结果表格 */ function TaskResultsSection({ tasks, currentConditions, manual, onOpenPanel }: { tasks: ScheduleTask[] currentConditions: SearchConditions /** 手动检索的结果(未执行过手动检索时为 null,当前检索标签页展示实时结果) */ manual: { ids: string[]; executed: SearchConditions } | null onOpenPanel: (s: AiPanelState) => void }) { const { profile, findProject } = useStore() const [activeId, setActiveId] = useState(manual ? 'current' : (tasks[0]?.id ?? 'current')) // 每次手动检索执行后,自动切到「当前检索」标签页 const prevManual = useRef(manual) useEffect(() => { if (manual && manual !== prevManual.current) setActiveId('current') prevManual.current = manual }, [manual]) const isCurrent = activeId === 'current' const active = tasks.find(t => t.id === activeId) ?? null const ids = useMemo(() => { const conds = isCurrent ? (manual?.executed ?? currentConditions) : active?.conditions if (!conds) return [] as string[] // 手动检索结果已按同一口径排序,直接复用;其余实时计算 if (isCurrent && manual) return manual.ids const list = runSearch(conds) if (profile.completed) { list.sort((a, b) => (matchScore(findProject(b)!, profile)?.score ?? -1) - (matchScore(findProject(a)!, profile)?.score ?? -1)) } return list }, [isCurrent, manual, currentConditions, active, profile, findProject]) if (!active && !isCurrent) return null const last = active?.runs[0] const activeConds = isCurrent ? (manual?.executed ?? currentConditions) : active!.conditions return (

检索结果

{tasks.map(t => ( ))}
{conditionsText(activeConds)} · {isCurrent ? ( {manual ? '手动检索' : '实时计算'} ) : ( 最近执行 {last?.time} )} · 共 {ids.length} 条{profile.completed ? ',按匹配度由高到低排序' : ''}
{ids.length === 0 ? (

这组条件下没有符合条件的项目

可在上方调整关键词、地区、预算或发布时间范围后重新检索

) : ( )}
) } /** 空态填充用的紧凑项目行:名称直达公告源网页,右侧直接给时间判断与 AI 分析入口 */ function ProjectPreviewRow({ p, onOpenPanel }: { p: Project; onOpenPanel: (s: AiPanelState) => void }) { const t = timeDigest(p) const toneCls = { urgent: 'text-bad-500', warn: 'text-warn-500', ok: 'text-ok-500', muted: 'text-ink-400' }[t.tone] return (
  • {p.name}
    {p.purchaser} · {p.region} · {p.budget === null ? '预算未披露' : {p.budget.toLocaleString()} 万元}
    {t.label}
  • ) }