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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
import React, { useEffect, useState } from 'react';
import {
  API,
  copy,
  isAdmin,
  showError,
  showSuccess,
  timestamp2string,
} from '../helpers';

import {
  Banner,
  Button,
  Form,
  ImagePreview,
  Layout,
  Modal,
  Progress,
  Table,
  Tag,
  Typography,
} from '@douyinfe/semi-ui';
import { ITEMS_PER_PAGE } from '../constants';
import { useTranslation } from 'react-i18next';

const colors = [
  'amber',
  'blue',
  'cyan',
  'green',
  'grey',
  'indigo',
  'light-blue',
  'lime',
  'orange',
  'pink',
  'purple',
  'red',
  'teal',
  'violet',
  'yellow',
];

const LogsTable = () => {
  const { t } = useTranslation();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modalContent, setModalContent] = useState('');
  function renderType(type) {
    
    switch (type) {
      case 'IMAGINE':
        return (
          <Tag color='blue' size='large'>

            {t('绘图')}

          </Tag>
        );
      case 'UPSCALE':
        return (
          <Tag color='orange' size='large'>

            {t('放大')}

          </Tag>
        );
      case 'VARIATION':
        return (
          <Tag color='purple' size='large'>

            {t('变换')}

          </Tag>
        );
      case 'HIGH_VARIATION':
        return (
          <Tag color='purple' size='large'>

            {t('强变换')}

          </Tag>
        );
      case 'LOW_VARIATION':
        return (
          <Tag color='purple' size='large'>

            {t('弱变换')}

          </Tag>
        );
      case 'PAN':
        return (
          <Tag color='cyan' size='large'>

            {t('平移')}

          </Tag>
        );
      case 'DESCRIBE':
        return (
          <Tag color='yellow' size='large'>

            {t('图生文')}

          </Tag>
        );
      case 'BLEND':
        return (
          <Tag color='lime' size='large'>

            {t('图混合')}

          </Tag>
        );
      case 'UPLOAD':
        return (
            <Tag color='blue' size='large'>

              上传文件

            </Tag>
        );
      case 'SHORTEN':
        return (
          <Tag color='pink' size='large'>

            {t('缩词')}

          </Tag>
        );
      case 'REROLL':
        return (
          <Tag color='indigo' size='large'>

            {t('重绘')}

          </Tag>
        );
      case 'INPAINT':
        return (
          <Tag color='violet' size='large'>

            {t('局部重绘-提交')}

          </Tag>
        );
      case 'ZOOM':
        return (
          <Tag color='teal' size='large'>

            {t('变焦')}

          </Tag>
        );
      case 'CUSTOM_ZOOM':
        return (
          <Tag color='teal' size='large'>

            {t('自定义变焦-提交')}

          </Tag>
        );
      case 'MODAL':
        return (
          <Tag color='green' size='large'>

            {t('窗口处理')}

          </Tag>
        );
      case 'SWAP_FACE':
        return (
          <Tag color='light-green' size='large'>

            {t('换脸')}

          </Tag>
        );
      default:
        return (
          <Tag color='white' size='large'>

            {t('未知')}

          </Tag>
        );
    }
  }
  
  function renderCode(code) {
    
    switch (code) {
      case 1:
        return (
          <Tag color='green' size='large'>

            {t('已提交')}

          </Tag>
        );
      case 21:
        return (
          <Tag color='lime' size='large'>

            {t('等待中')}

          </Tag>
        );
      case 22:
        return (
          <Tag color='orange' size='large'>

            {t('重复提交')}

          </Tag>
        );
      case 0:
        return (
          <Tag color='yellow' size='large'>

            {t('未提交')}

          </Tag>
        );
      default:
        return (
          <Tag color='white' size='large'>

            {t('未知')}

          </Tag>
        );
    }
  }
  
  function renderStatus(type) {
    
    switch (type) {
      case 'SUCCESS':
        return (
          <Tag color='green' size='large'>

            {t('成功')}

          </Tag>
        );
      case 'NOT_START':
        return (
          <Tag color='grey' size='large'>

            {t('未启动')}

          </Tag>
        );
      case 'SUBMITTED':
        return (
          <Tag color='yellow' size='large'>

            {t('队列中')}

          </Tag>
        );
      case 'IN_PROGRESS':
        return (
          <Tag color='blue' size='large'>

            {t('执行中')}

          </Tag>
        );
      case 'FAILURE':
        return (
          <Tag color='red' size='large'>

            {t('失败')}

          </Tag>
        );
      case 'MODAL':
        return (
          <Tag color='yellow' size='large'>

            {t('窗口等待')}

          </Tag>
        );
      default:
        return (
          <Tag color='white' size='large'>

            {t('未知')}

          </Tag>
        );
    }
  }
  
  const renderTimestamp = (timestampInSeconds) => {
    const date = new Date(timestampInSeconds * 1000); // 从秒转换为毫秒
  
    const year = date.getFullYear(); // 获取年份
    const month = ('0' + (date.getMonth() + 1)).slice(-2); // 获取月份,从0开始需要+1,并保证两位数
    const day = ('0' + date.getDate()).slice(-2); // 获取日期,并保证两位数
    const hours = ('0' + date.getHours()).slice(-2); // 获取小时,并保证两位数
    const minutes = ('0' + date.getMinutes()).slice(-2); // 获取分钟,并保证两位数
    const seconds = ('0' + date.getSeconds()).slice(-2); // 获取秒钟,并保证两位数
  
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; // 格式化输出
  };
  // 修改renderDuration函数以包含颜色逻辑
  function renderDuration(submit_time, finishTime) {
    
    if (!submit_time || !finishTime) return 'N/A';

    const start = new Date(submit_time);
    const finish = new Date(finishTime);
    const durationMs = finish - start;
    const durationSec = (durationMs / 1000).toFixed(1);
    const color = durationSec > 60 ? 'red' : 'green';

    return (
      <Tag color={color} size="large">

        {durationSec} {t('秒')}

      </Tag>
    );
  }
  const columns = [
    {
      title: t('提交时间'),
      dataIndex: 'submit_time',
      render: (text, record, index) => {
        return <div>{renderTimestamp(text / 1000)}</div>;
      },
    },
    {
      title: t('花费时间'),
      dataIndex: 'finish_time', // 以finish_time作为dataIndex
      key: 'finish_time',
      render: (finish, record) => {
        // 假设record.start_time是存在的,并且finish是完成时间的时间戳
        return renderDuration(record.submit_time, finish);
      },
    },
    {
      title: t('渠道'),
      dataIndex: 'channel_id',
      className: isAdmin() ? 'tableShow' : 'tableHiddle',
      render: (text, record, index) => {
        return (
          <div>

            <Tag

              color={colors[parseInt(text) % colors.length]}

              size='large'

              onClick={() => {

                copyText(text); // 假设copyText是用于文本复制的函数

              }}

            >

              {' '}

              {text}{' '}

            </Tag>

          </div>
        );
      },
    },
    {
      title: t('类型'),
      dataIndex: 'action',
      render: (text, record, index) => {
        return <div>{renderType(text)}</div>;
      },
    },
    {
      title: t('任务ID'),
      dataIndex: 'mj_id',
      render: (text, record, index) => {
        return <div>{text}</div>;
      },
    },
    {
      title: t('提交结果'),
      dataIndex: 'code',
      className: isAdmin() ? 'tableShow' : 'tableHiddle',
      render: (text, record, index) => {
        return <div>{renderCode(text)}</div>;
      },
    },
    {
      title: t('任务状态'),
      dataIndex: 'status',
      className: isAdmin() ? 'tableShow' : 'tableHiddle',
      render: (text, record, index) => {
        return <div>{renderStatus(text)}</div>;
      },
    },
    {
      title: t('进度'),
      dataIndex: 'progress',
      render: (text, record, index) => {
        return (
          <div>

            {

              // 转换例如100%为数字100,如果text未定义,返回0

              <Progress

                stroke={

                  record.status === 'FAILURE'

                    ? 'var(--semi-color-warning)'

                    : null

                }

                percent={text ? parseInt(text.replace('%', '')) : 0}

                showInfo={true}

                aria-label='drawing progress'

              />

            }

          </div>
        );
      },
    },
    {
      title: t('结果图片'),
      dataIndex: 'image_url',
      render: (text, record, index) => {
        if (!text) {
          return t('无');
        }
        return (
          <Button

            onClick={() => {

              setModalImageUrl(text); // 更新图片URL状态

              setIsModalOpenurl(true); // 打开模态框

            }}

          >

            {t('查看图片')}

          </Button>
        );
      },
    },
    {
      title: 'Prompt',
      dataIndex: 'prompt',
      render: (text, record, index) => {
        // 如果text未定义,返回替代文本,例如空字符串''或其他
        if (!text) {
          return t('无');
        }

        return (
          <Typography.Text

            ellipsis={{ showTooltip: true }}

            style={{ width: 100 }}

            onClick={() => {

              setModalContent(text);

              setIsModalOpen(true);

            }}

          >

            {text}

          </Typography.Text>
        );
      },
    },
    {
      title: 'PromptEn',
      dataIndex: 'prompt_en',
      render: (text, record, index) => {
        // 如果text未定义,返回替代文本,例如空字符串''或其他
        if (!text) {
          return t('无');
        }

        return (
          <Typography.Text

            ellipsis={{ showTooltip: true }}

            style={{ width: 100 }}

            onClick={() => {

              setModalContent(text);

              setIsModalOpen(true);

            }}

          >

            {text}

          </Typography.Text>
        );
      },
    },
    {
      title: t('失败原因'),
      dataIndex: 'fail_reason',
      render: (text, record, index) => {
        // 如果text未定义,返回替代文本,例如空字符串''或其他
        if (!text) {
          return t('无');
        }

        return (
          <Typography.Text

            ellipsis={{ showTooltip: true }}

            style={{ width: 100 }}

            onClick={() => {

              setModalContent(text);

              setIsModalOpen(true);

            }}

          >

            {text}

          </Typography.Text>
        );
      },
    },
  ];

  const [logs, setLogs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [activePage, setActivePage] = useState(1);
  const [logCount, setLogCount] = useState(ITEMS_PER_PAGE);
  const [logType, setLogType] = useState(0);
  const isAdminUser = isAdmin();
  const [isModalOpenurl, setIsModalOpenurl] = useState(false);
  const [showBanner, setShowBanner] = useState(false);

  // 定义模态框图片URL的状态和更新函数
  const [modalImageUrl, setModalImageUrl] = useState('');
  let now = new Date();
  // 初始化start_timestamp为前一天
  const [inputs, setInputs] = useState({
    channel_id: '',
    mj_id: '',
    start_timestamp: timestamp2string(now.getTime() / 1000 - 2592000),
    end_timestamp: timestamp2string(now.getTime() / 1000 + 3600),
  });
  const { channel_id, mj_id, start_timestamp, end_timestamp } = inputs;

  const [stat, setStat] = useState({
    quota: 0,
    token: 0,
  });

  const handleInputChange = (value, name) => {
    setInputs((inputs) => ({ ...inputs, [name]: value }));
  };

  const setLogsFormat = (logs) => {
    for (let i = 0; i < logs.length; i++) {
      logs[i].timestamp2string = timestamp2string(logs[i].created_at);
      logs[i].key = '' + logs[i].id;
    }
    // data.key = '' + data.id
    setLogs(logs);
    setLogCount(logs.length + ITEMS_PER_PAGE);
    // console.log(logCount);
  };

  const loadLogs = async (startIdx) => {
    setLoading(true);

    let url = '';
    let localStartTimestamp = Date.parse(start_timestamp);
    let localEndTimestamp = Date.parse(end_timestamp);
    if (isAdminUser) {
      url = `/api/mj/?p=${startIdx}&channel_id=${channel_id}&mj_id=${mj_id}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}`;
    } else {
      url = `/api/mj/self/?p=${startIdx}&mj_id=${mj_id}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}`;
    }
    const res = await API.get(url);
    const { success, message, data } = res.data;
    if (success) {
      if (startIdx === 0) {
        setLogsFormat(data);
      } else {
        let newLogs = [...logs];
        newLogs.splice(startIdx * ITEMS_PER_PAGE, data.length, ...data);
        setLogsFormat(newLogs);
      }
    } else {
      showError(message);
    }
    setLoading(false);
  };

  const pageData = logs.slice(
    (activePage - 1) * ITEMS_PER_PAGE,
    activePage * ITEMS_PER_PAGE,
  );

  const handlePageChange = (page) => {
    setActivePage(page);
    if (page === Math.ceil(logs.length / ITEMS_PER_PAGE) + 1) {
      // In this case we have to load more data and then append them.
      loadLogs(page - 1).then((r) => {});
    }
  };

  const refresh = async () => {
    // setLoading(true);
    setActivePage(1);
    await loadLogs(0);
  };

  const copyText = async (text) => {
    if (await copy(text)) {
      showSuccess('已复制:' + text);
    } else {
      // setSearchKeyword(text);
      Modal.error({ title: '无法复制到剪贴板,请手动复制', content: text });
    }
  };

  useEffect(() => {
    refresh().then();
  }, [logType]);

  useEffect(() => {
    const mjNotifyEnabled = localStorage.getItem('mj_notify_enabled');
    if (mjNotifyEnabled !== 'true') {
      setShowBanner(true);
    }
  }, []);

  return (
    <>

      <Layout>

        {isAdminUser && showBanner ? (

          <Banner

            type='info'

            description={t('当前未开启Midjourney回调部分项目可能无法获得绘图结果可在运营设置中开启。')}

          />

        ) : (

          <></>

        )}

        <Form layout='horizontal' style={{ marginTop: 10 }}>

          <>

            <Form.Input

              field='channel_id'

              label={t('渠道 ID')}

              style={{ width: 176 }}

              value={channel_id}

              placeholder={t('可选值')}

              name='channel_id'

              onChange={(value) => handleInputChange(value, 'channel_id')}

            />

            <Form.Input

              field='mj_id'

              label={t('任务 ID')}

              style={{ width: 176 }}

              value={mj_id}

              placeholder={t('可选值')}

              name='mj_id'

              onChange={(value) => handleInputChange(value, 'mj_id')}

            />

            <Form.DatePicker

              field='start_timestamp'

              label={t('起始时间')}

              style={{ width: 272 }}

              initValue={start_timestamp}

              value={start_timestamp}

              type='dateTime'

              name='start_timestamp'

              onChange={(value) => handleInputChange(value, 'start_timestamp')}

            />

            <Form.DatePicker

              field='end_timestamp'

              fluid

              label={t('结束时间')}

              style={{ width: 272 }}

              initValue={end_timestamp}

              value={end_timestamp}

              type='dateTime'

              name='end_timestamp'

              onChange={(value) => handleInputChange(value, 'end_timestamp')}

            />



            <Form.Section>

              <Button

                label={t('查询')}

                type='primary'

                htmlType='submit'

                className='btn-margin-right'

                onClick={refresh}

              >

                {t('查询')}

              </Button>

            </Form.Section>

          </>

        </Form>

        <Table

          style={{ marginTop: 5 }}

          columns={columns}

          dataSource={pageData}

          pagination={{

            currentPage: activePage,

            pageSize: ITEMS_PER_PAGE,

            total: logCount,

            pageSizeOpts: [10, 20, 50, 100],

            onPageChange: handlePageChange,

            formatPageText: (page) =>

              t('第 {{start}} - {{end}} 条,共 {{total}} 条', {

                start: page.currentStart,

                end: page.currentEnd,

                total: logCount

              }),

          }}

          loading={loading}

        />

        <Modal

          visible={isModalOpen}

          onOk={() => setIsModalOpen(false)}

          onCancel={() => setIsModalOpen(false)}

          closable={null}

          bodyStyle={{ height: '400px', overflow: 'auto' }} // 设置模态框内容区域样式

          width={800} // 设置模态框宽度

        >

          <p style={{ whiteSpace: 'pre-line' }}>{modalContent}</p>

        </Modal>

        <ImagePreview

          src={modalImageUrl}

          visible={isModalOpenurl}

          onVisibleChange={(visible) => setIsModalOpenurl(visible)}

        />

      </Layout>

    </>
  );
};

export default LogsTable;