tony.cheng
2026-02-09 d31819515e4aac228f26e7cbb92c89e0f520e8ac
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { message } from 'antd';
import OutboundBotAPIService from '../../services/OutboundBotAPIService';
 
// 常量配置
const OUTBOUND_JOBS_KEY = 'outbound_call_jobs';
const POLL_INTERVAL = 10000; // 10秒轮询间隔
const MAX_POLL_DURATION = 7200000; // 2小时最大轮询时长(毫秒)
const MAX_RETRY_COUNT = 10; // 最大重试次数
 
// 活跃状态和终态定义
const ACTIVE_STATUSES = ['Scheduling', 'Executing', 'Paused', 'Drafted'];
const TERMINAL_STATUSES = ['Succeeded', 'Failed', 'Cancelled'];
 
// 状态中文映射
const STATUS_MAP = {
  'Scheduling': '拨号中',
  'Executing': '通话中',
  'Succeeded': '通话成功',
  'Paused': '暂停',
  'Failed': '通话失败',
  'Cancelled': '通话已取消',
  'Drafted': '草稿'
};
 
/**
 * 智能外呼通话显示组件
 * 基于 localStorage 中的 jobId 轮询查询通话状态
 * 支持多任务并行显示、自动清理终态任务
 */
const OutboundCallWidget = () => {
  const [isVisible, setIsVisible] = useState(true);
  const [isMinimized, setIsMinimized] = useState(false);
  const [calls, setCalls] = useState([]);
  const isMountedRef = useRef(true);
 
  /**
   * 格式化通话时长
   * @param {number} startTime - 开始时间戳(毫秒)
   * @returns {string} 格式化的时长(MM:SS)
   */
  const formatDuration = (startTime) => {
    if (!startTime) return '00:00';
    const seconds = Math.floor((Date.now() - startTime) / 1000);
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };
 
  /**
   * 从 localStorage 读取外呼任务
   * @returns {Array} 任务数组
   */
  const loadJobsFromStorage = () => {
    try {
      const stored = localStorage.getItem(OUTBOUND_JOBS_KEY);
      if (!stored) return [];
      return JSON.parse(stored);
    } catch (err) {
      console.error('读取外呼任务失败:', err);
      return [];
    }
  };
 
  /**
   * 保存任务到 localStorage
   * @param {Array} jobs - 任务数组
   */
  const saveJobsToStorage = (jobs) => {
    try {
      if (jobs.length === 0) {
        localStorage.removeItem(OUTBOUND_JOBS_KEY);
      } else {
        localStorage.setItem(OUTBOUND_JOBS_KEY, JSON.stringify(jobs));
      }
    } catch (err) {
      console.error('保存外呼任务失败:', err);
    }
  };
 
  /**
   * 移除终态或超时的任务
   * @param {Array} jobs - 当前任务数组
   * @returns {Array} 清理后的任务数组
   */
  const cleanupJobs = (jobs) => {
    const now = Date.now();
    return jobs.filter(job => {
      // 检查是否超时(2小时)
      if (now - job.pollStartTime > MAX_POLL_DURATION) {
        console.warn('外呼轮询超时(2小时),自动停止,jobId:', job.jobId);
        return false;
      }
      // 保留活跃状态
      return ACTIVE_STATUSES.includes(job.callStatus);
    });
  };
 
  /**
   * 查询通话状态(轮询核心逻辑)
   */
  const fetchCallStatus = useCallback(async () => {
    let jobs = loadJobsFromStorage();
    
    // 过滤出活跃任务
    const activeJobs = jobs.filter(job => ACTIVE_STATUSES.includes(job.callStatus));
    
    if (activeJobs.length === 0) {
      setCalls([]);
      return;
    }
 
    console.log('轮询查询通话状态,任务数量:', activeJobs.length);
 
    // 遍历所有活跃任务,逐个查询状态(caseRef 和 jobId 都是必传参数)
    const updatedJobs = await Promise.all(
      activeJobs.map(async (job) => {
        try {
          // 同时传入 caseRef 和 jobId
          const response = await OutboundBotAPIService.getCallStatus({ 
            caseRef: job.caseId,
            jobId: job.jobId 
          });
          
          if (response?.data) {
            const newStatus = response.data.callStatus;
            
            // 更新任务状态
            const updatedJob = {
              ...job,
              callStatus: newStatus,
              retryCount: 0 // 成功后重置重试计数
            };
 
            // 检测终态
            if (TERMINAL_STATUSES.includes(newStatus)) {
              console.log('检测到终态,jobId:', job.jobId, ', status:', newStatus);
              return null; // 标记为删除
            }
 
            return updatedJob;
          }
          
          return job;
        } catch (err) {
          console.warn('查询失败,重试次数:', job.retryCount + 1, '/', MAX_RETRY_COUNT, ', jobId:', job.jobId, ', 错误:', err.message);
          
          // 累加重试计数
          const retryCount = job.retryCount + 1;
          
          if (retryCount >= MAX_RETRY_COUNT) {
            console.error('重试次数超限,jobId:', job.jobId);
            message.error('外呼状态查询失败次数过多,已停止监控');
            return null; // 标记为删除
          }
          
          return { ...job, retryCount };
        }
      })
    );
 
    // 过滤掉标记为删除的任务(null)
    const filteredJobs = updatedJobs.filter(job => job !== null);
    
    // 清理超时任务
    const cleanedJobs = cleanupJobs(filteredJobs);
 
    // 保存到 localStorage
    saveJobsToStorage(cleanedJobs);
 
    // 更新组件状态
    if (isMountedRef.current) {
      setCalls(cleanedJobs);
    }
  }, []);
 
  // 定时轮询通话状态
  useEffect(() => {
    // 初始加载
    fetchCallStatus();
    
    // 设置轮询定时器(10秒间隔)
    const interval = setInterval(fetchCallStatus, POLL_INTERVAL);
    
    // 清理函数
    return () => {
      clearInterval(interval);
      isMountedRef.current = false;
    };
  }, [fetchCallStatus]);
 
  // 组件挂载时标记
  useEffect(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
    };
  }, []);
 
  // 关闭气泡
  const handleClose = (e) => {
    e.stopPropagation();
    setIsVisible(false);
    setIsMinimized(true);
  };
 
  // 展开气泡
  const handleExpand = () => {
    setIsMinimized(false);
    setIsVisible(true);
  };
 
  // 如果最小化,显示AI客服图标
  if (isMinimized) {
 
 
    return (
      <div
        onClick={handleExpand}
        style={{
          position: 'fixed',
          right: 20,
          bottom: 80,
          width: 56,
          height: 56,
          borderRadius: '50%',
          background: 'linear-gradient(135deg, #1A6FB8 0%, #0d4a8a 100%)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          cursor: 'pointer',
          boxShadow: '0 4px 12px rgba(26, 111, 184, 0.4)',
          zIndex: 1000,
          transition: 'all 0.3s ease',
        }}
        onMouseEnter={(e) => {
          e.currentTarget.style.transform = 'scale(1.1)';
        }}
        onMouseLeave={(e) => {
          e.currentTarget.style.transform = 'scale(1)';
        }}
      >
        <i
          className="fas fa-headset"
          style={{
            fontSize: 24,
            color: 'white',
          }}
        />
        {/* 红点提示有通话 */}
        {calls.length > 0 && (
          <div
            style={{
              position: 'absolute',
              top: -2,
              right: -2,
              width: 16,
              height: 16,
              borderRadius: '50%',
              background: '#ff4d4f',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: 10,
              color: 'white',
              fontWeight: 'bold',
            }}
          >
            {calls.length}
          </div>
        )}
      </div>
    );
  }
 
  // 展开状态 - 显示通话气泡
  return (
    <div
      style={{
        position: 'fixed',
        right: 20,
        bottom: 80,
        zIndex: 1000,
        display: 'flex',
        flexDirection: 'column',
        gap: 10,
        maxWidth: 320,
      }}
    >
      {calls.map((call, index) => (
        <div
          key={call.jobId || call.phoneNumber || index}
          style={{
            background: 'linear-gradient(135deg, #1A6FB8 0%, #0d4a8a 100%)',
            borderRadius: 12,
            padding: '16px 20px',
            color: 'white',
            boxShadow: '0 4px 16px rgba(26, 111, 184, 0.3)',
            position: 'relative',
            minWidth: 280,
          }}
        >
          {/* 关闭按钮 */}
          <button
            onClick={handleClose}
            style={{
              position: 'absolute',
              top: 8,
              right: 8,
              width: 24,
              height: 24,
              borderRadius: '50%',
              border: 'none',
              background: 'rgba(255,255,255,0.2)',
              color: 'white',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: 14,
              transition: 'all 0.2s ease',
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.background = 'rgba(255,255,255,0.3)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = 'rgba(255,255,255,0.2)';
            }}
          >
            <i className="fas fa-times" />
          </button>
 
          {/* 头部 - 智能体工作中 */}
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: 10,
              marginBottom: 12,
            }}
          >
            <div
              style={{
                width: 36,
                height: 36,
                borderRadius: '50%',
                background: 'rgba(255,255,255,0.2)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <i className="fas fa-robot" style={{ fontSize: 18 }} />
            </div>
            <div style={{ flex: 1 }}>
              <div
                style={{
                  fontSize: 16,
                  fontWeight: 600,
                  display: 'flex',
                  alignItems: 'center',
                  gap: 8,
                }}
              >
                智能体工作中
                <span
                  style={{
                    width: 8,
                    height: 8,
                    borderRadius: '50%',
                    background: '#52c41a',
                    animation: 'pulse 2s infinite',
                  }}
                />
              </div>
            </div>
          </div>
 
          {/* 通话信息 */}
          <div style={{ marginBottom: 10 }}>
            <div style={{ fontSize: 14, opacity: 0.9, lineHeight: 1.5 }}>
              正在与 {call.personId || '未知联系人'} 电话沟通中...
            </div>
            <div style={{ fontSize: 12, opacity: 0.75, marginTop: 4 }}>
              状态:{STATUS_MAP[call.callStatus] || call.callStatus}
            </div>
          </div>
 
          {/* 通话时长 */}
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: 6,
              fontSize: 13,
              opacity: 0.85,
            }}
          >
            <i className="far fa-clock" />
            <span>已持续: {formatDuration(call.startTime)}</span>
          </div>
        </div>
      ))}
 
      {/* 无通话时的占位提示 */}
      {calls.length === 0 && isVisible && (
        <div
          style={{
            background: 'linear-gradient(135deg, #1A6FB8 0%, #0d4a8a 100%)',
            borderRadius: 12,
            padding: '16px 20px',
            color: 'white',
            boxShadow: '0 4px 16px rgba(26, 111, 184, 0.3)',
            position: 'relative',
            minWidth: 280,
          }}
        >
          {/* 关闭按钮 */}
          <button
            onClick={handleClose}
            style={{
              position: 'absolute',
              top: 8,
              right: 8,
              width: 24,
              height: 24,
              borderRadius: '50%',
              border: 'none',
              background: 'rgba(255,255,255,0.2)',
              color: 'white',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: 14,
            }}
          >
            <i className="fas fa-times" />
          </button>
 
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div
              style={{
                width: 36,
                height: 36,
                borderRadius: '50%',
                background: 'rgba(255,255,255,0.2)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <i className="fas fa-robot" style={{ fontSize: 18 }} />
            </div>
            <div>
              <div style={{ fontSize: 16, fontWeight: 600 }}>智能外呼系统</div>
              <div style={{ fontSize: 13, opacity: 0.85 }}>暂无进行中的通话</div>
            </div>
          </div>
        </div>
      )}
 
      {/* CSS 动画 */}
      <style>{`
        @keyframes pulse {
          0%, 100% { opacity: 1; }
          50% { opacity: 0.5; }
        }
      `}</style>
    </div>
  );
};
 
export default OutboundCallWidget;