File size: 10,929 Bytes
ef785b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import { useState, useRef, useCallback, useEffect } from 'react'
import { generateReport } from '../api'
import PipelineFlow from '../components/PipelineFlow'
import RadarChart from '../components/RadarChart'
import ReportCard from '../components/ReportCard'

const INITIAL_STEPS = [
  { id: 'agent1', label: '简历解析', status: 'idle' },
  { id: 'agent2', label: '匹配诊断', status: 'idle' },
  { id: 'agent3', label: '报告生成', status: 'idle' },
]

function DiagnosePage({ jobId, jobData, resumeData, onComplete, onBack, onGoHome }) {
  const [pageStatus, setPageStatus] = useState('idle')
  const [steps, setSteps] = useState(INITIAL_STEPS)
  const [viewType, setViewType] = useState('student')
  const [jdParsed, setJdParsed] = useState(null)
  const [matchReport, setMatchReport] = useState(null)
  const [advice, setAdvice] = useState(null)
  const [errorMsg, setErrorMsg] = useState('')
  const abortRef = useRef(null)
  const retryCountRef = useRef(0)
  const retryTimeoutRef = useRef(null)

  const jobInfo = jobData || {
    name: '岗位名称',
    company: '公司名称',
    city: '',
    salary: '',
    tags: [],
    description: '',
    requirements: '',
    expectation_signals: []
  }

  const updateStep = useCallback((agentId, newStatus) => {
    setSteps((prev) => prev.map((s) => (s.id === agentId ? { ...s, status: newStatus } : s)))
  }, [])

  const handleAnalyze = useCallback(async () => {
    setPageStatus('loading')
    setSteps(INITIAL_STEPS.map((s) => ({ ...s, status: 'idle' })))
    setJdParsed(null)
    setMatchReport(null)
    setAdvice(null)
    retryCountRef.current = 0

    const controller = new AbortController()
    abortRef.current = controller

    const doFetch = async () => {
      try {
        const response = await generateReport(jobId, resumeData)
        if (!response.ok) throw new Error('请求失败')
        const reader = response.body.getReader()
        const decoder = new TextDecoder()
        let buffer = ''

        while (true) {
          const { done, value } = await reader.read()
          if (done) break

          buffer += decoder.decode(value, { stream: true })
          const lines = buffer.split('\n')
          buffer = lines.pop() || ''

          for (const line of lines) {
            const trimmed = line.trim()
            if (!trimmed) continue
            const jsonStr = trimmed.startsWith('data: ') ? trimmed.slice(6).trim() : trimmed
            if (!jsonStr) continue
            try {
              const event = JSON.parse(jsonStr)
              const { type, agent, data } = event

              if (type === 'agent_start') {
                updateStep(agent, 'running')
              } else if (type === 'agent_complete') {
                updateStep(agent, 'completed')
                if (agent === 'agent1' && data) setJdParsed(data)
                if (agent === 'agent2' && data) setMatchReport(data)
                if (agent === 'agent3' && data) setAdvice(data)
              } else if (type === 'report_complete') {
                if (data) {
                  if (data.jd_parsed) setJdParsed(data.jd_parsed)
                  if (data.match_report) setMatchReport(data.match_report)
                  if (data.advice) setAdvice(data.advice)
                }
              } else if (type === 'error') {
                updateStep(agent || 'agent3', 'error')
              }
            } catch {
              // skip
            }
          }
        }

        setPageStatus('success')
      } catch (err) {
        if (err.name === 'AbortError') return
        retryCountRef.current += 1
        if (retryCountRef.current <= 3) {
          const delay = retryCountRef.current * 1000
          retryTimeoutRef.current = setTimeout(doFetch, delay)
        } else {
          setPageStatus('error')
          setErrorMsg('连接中断,请刷新页面')
        }
      }
    }

    doFetch()
  }, [jobId, updateStep])

  const abort = useCallback(() => {
    clearTimeout(retryTimeoutRef.current)
    abortRef.current?.abort()
    setPageStatus('idle')
  }, [])

  useEffect(() => {
    return () => {
      clearTimeout(retryTimeoutRef.current)
      abortRef.current?.abort()
    }
  }, [])

  const studentDims = matchReport?.dimensions?.map(d => d.name) || []
  const studentScores = matchReport?.dimensions?.map(d => d.score) || []
  const studentEvidence = matchReport?.dimensions?.map(d => d.evidence) || []

  const hrViewData = matchReport?.hr_view || {}

  const showResults = pageStatus === 'loading' || pageStatus === 'success' || pageStatus === 'error'
  const analyzeDone = pageStatus === 'success'

  if (!resumeData) {
    return (
      <div className="empty-state card">
        <h2 className="font-bold text-xl mb-16">匹配诊断</h2>
        <p className="text-secondary mb-24">请先上传或填写简历,才能进行匹配诊断</p>
        <div className="flex-center gap-12">
          <button className="btn btn-primary" onClick={onGoHome}>上传简历</button>
          <button className="btn btn-secondary" onClick={onGoHome}>手工填写</button>
        </div>
        <div className="mt-16">
          <button className="btn btn-secondary" onClick={onBack}>返回推荐</button>
        </div>
      </div>
    )
  }

  return (
    <div>
      <div className="card mb-24">
        <div className="flex-between mb-8 flex-wrap">
          <div className="min-width-0 flex-1">
            <h2 className="font-bold text-xl">{jobInfo.name}</h2>
            <p className="text-secondary">{jobInfo.company} · {jobInfo.city || ''} {jobInfo.salary ? '· ' + jobInfo.salary : ''}</p>
          </div>
          <div className="flex gap-8 flex-wrap justify-end max-w-50p">
            {(jobInfo.tags || []).map((tag, i) => (
              <span key={i} className="tag">{tag}</span>
            ))}
          </div>
        </div>

        {jobInfo.description && (
          <div className="mb-12">
            <h4 className="font-bold text-sm mb-4">职位描述</h4>
            <p className="text-sm text-secondary whitespace-pre-wrap">{jobInfo.description}</p>
          </div>
        )}

        {jobInfo.requirements && (
          <div className="mb-12">
            <h4 className="font-bold text-sm mb-4">职位要求</h4>
            <p className="text-sm text-secondary whitespace-pre-wrap">{jobInfo.requirements}</p>
          </div>
        )}

        {jobInfo.expectation_signals && jobInfo.expectation_signals.length > 0 && (
          <div className="mb-12">
            <h4 className="font-bold text-sm mb-4">岗位画像</h4>
            <div className="flex flex-col gap-8">
              {jobInfo.expectation_signals.map((signal, i) => {
                const pct = Math.round((signal.confidence || 0) * 100)
                const barColor = (signal.confidence || 0) > 0.7
                  ? 'var(--color-success)'
                  : (signal.confidence || 0) > 0.4
                    ? 'var(--color-warning)'
                    : 'var(--color-error)'
                return (
                  <div key={i} className="info-box">
                    <div className="flex-between mb-4">
                      <span className="text-sm font-bold">{signal.tag || signal.name}</span>
                      <span className="text-xs text-light">可信度 {pct}%</span>
                    </div>
                    <p className="text-xs text-secondary mb-4">{signal.evidence || ''}</p>
                    <div className="progress-track">
                      <div className="progress-bar" style={{ width: `${pct}%`, backgroundColor: barColor }} />
                    </div>
                  </div>
                )
              })}
            </div>
          </div>
        )}
      </div>

      {pageStatus === 'idle' && (
        <div className="card mb-24 bg-light">
          <h4 className="font-bold mb-8">分析流程说明</h4>
          <p className="text-sm text-secondary mb-12">分析将由 3 个 AI Agent 依次完成:</p>
          <div className="flex flex-col gap-8">
            <div className="card p-8 px-12">
              <span className="text-sm font-bold">① JD 解析器</span>
              <p className="text-xs text-secondary mt-4">提取岗位核心要求、技术栈、加分项、文化信号</p>
            </div>
            <div className="card p-8 px-12">
              <span className="text-sm font-bold">② 匹配诊断器</span>
              <p className="text-xs text-secondary mt-4">多维度拆解匹配度,输出分数和引用证据</p>
            </div>
            <div className="card p-8 px-12">
              <span className="text-sm font-bold">③ 建议生成器</span>
              <p className="text-xs text-secondary mt-4">生成简历修改建议和面试准备方向</p>
            </div>
          </div>
          <button className="btn btn-primary mt-16" onClick={handleAnalyze}>开始分析</button>
        </div>
      )}

      {showResults && (
        <>
          <div className="card mb-24"><PipelineFlow steps={steps} /></div>
          {pageStatus !== 'loading' && matchReport && (
            <>
              <div className="flex gap-12 mb-24 flex-wrap">
                <button className={`btn ${viewType === 'student' ? 'btn-primary' : 'btn-secondary'}`} onClick={() => setViewType('student')}>学生视角</button>
                <button className={`btn ${viewType === 'hr' ? 'btn-primary' : 'btn-secondary'}`} onClick={() => setViewType('hr')}>HR 视角</button>
              </div>
              {viewType === 'student' ? (
                <>
                  <div className="card mb-24"><RadarChart dimensions={studentDims} scores={studentScores} /></div>
                  <div className="flex flex-col gap-16">
                    {studentDims.map((dim, i) => (
                      <ReportCard key={dim} dimension={dim} score={studentScores[i]} evidence={studentEvidence[i]} viewType={viewType} />
                    ))}
                  </div>
                </>
              ) : (
                <div className="flex flex-col gap-16">
                  <ReportCard dimension="HR 快速筛查模拟" viewType="hr" hrView={hrViewData} />
                </div>
              )}
            </>
          )}
          {pageStatus === 'error' && (
            <div className="error-state">
              <p className="error-state-text">{errorMsg}</p>
              <button className="btn btn-primary" onClick={handleAnalyze}>重新分析</button>
            </div>
          )}
        </>
      )}

      {analyzeDone && (
        <div className="mt-24 flex-center gap-12 flex-wrap">
          <button className="btn btn-primary" onClick={() => onComplete({ advice })}>查看改进建议</button>
          <button className="btn btn-secondary" onClick={onBack}>返回推荐</button>
        </div>
      )}
    </div>
  )
}

export default DiagnosePage