Files
monkey-ai-web/src/components/promotion/PromotionPosterModal.jsx
T
zhanjunhao 8a48765a46 chore(repo): 移除重复版权文件头并纳入共享单测
集中保留原版权声明,移除文件头检查和全局测试忽略规则。验证:全量单测、受影响用例复测及静态检查通过。
2026-11-20 11:23:49 +08:00

517 lines
15 KiB
React

import {
Copy as ActionCopy,
Download as ActionDownload,
} from '@/components/common/icons/ActionIcons';
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import {
Modal,
Button,
Typography,
Tabs,
Input,
Alert,
Skeleton,
Radio,
} from 'antd';
import { QRCodeCanvas } from 'qrcode.react';
import { Smartphone, Monitor, Gift, Users, ChevronRight } from 'lucide-react';
import './promotion-poster.css';
import { API, showError, showSuccess, copy } from '../../helpers';
const { Text, Title, Paragraph } = Typography;
// 默认海报模板配置
const DEFAULT_TEMPLATES = [
{
id: 'blue',
name: '科技蓝',
bgGradient: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
textColor: '#ffffff',
},
{
id: 'orange',
name: '活力橙',
bgGradient: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
textColor: '#ffffff',
},
{
id: 'green',
name: '清新绿',
bgGradient: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
textColor: '#ffffff',
},
{
id: 'dark',
name: '暗夜黑',
bgGradient: 'linear-gradient(135deg, #232526 0%, #414345 100%)',
textColor: '#ffffff',
},
];
const PromotionPosterModal = ({ visible, onClose }) => {
const { t } = useTranslation();
const navigate = useNavigate();
const canvasRef = useRef(null);
const [loading, setLoading] = useState(true);
const [affCode, setAffCode] = useState('');
const [affLink, setAffLink] = useState('');
const [systemName, setSystemName] = useState('');
const [selectedTemplate, setSelectedTemplate] = useState(
DEFAULT_TEMPLATES[0],
);
const [downloading, setDownloading] = useState(false);
const [posterConfig, setPosterConfig] = useState(null);
const [activeTab, setActiveTab] = useState('link');
// 获取邀请码
const fetchAffCode = async () => {
try {
const res = await API.get('/api/user/aff');
if (res.data.success) {
const code = res.data.data;
setAffCode(code);
const link =
typeof code === 'string' && code.startsWith('http')
? code
: `${window.location.origin}/register?aff=${code}`;
setAffLink(link);
}
} catch (error) {
console.error('获取邀请码失败:', error);
}
};
// 获取系统名称
const fetchSystemName = async () => {
try {
const res = await API.get('/api/status');
if (res.data.success) {
setSystemName(res.data.data.system_name || 'AI Platform');
}
} catch {
setSystemName('AI Platform');
}
};
// 获取海报配置
const fetchPosterConfig = async () => {
try {
const res = await API.get('/api/poster/config');
if (res.data.success && res.data.data) {
setPosterConfig(res.data.data);
}
} catch {
// 使用默认配置
}
};
useEffect(() => {
if (visible) {
setLoading(true);
Promise.all([
fetchAffCode(),
fetchSystemName(),
fetchPosterConfig(),
]).finally(() => {
setLoading(false);
});
}
}, [visible]);
// 绘制海报内容
const drawContent = useCallback(
(ctx, width, height) => {
const textColor = selectedTemplate.textColor;
ctx.fillStyle = textColor;
ctx.font =
'bold 28px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
ctx.textAlign = 'center';
ctx.fillText(
posterConfig?.slogan || t('邀请好友,共享AI'),
width / 2,
80,
);
ctx.font =
'16px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
ctx.fillText(
posterConfig?.sub_slogan || t('注册即可获得免费额度'),
width / 2,
115,
);
ctx.font =
'bold 24px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
ctx.fillText(systemName, width / 2, 180);
const qrSize = 180;
const qrX = (width - qrSize - 20) / 2;
const qrY = 230;
ctx.fillStyle = '#ffffff';
ctx.beginPath();
ctx.roundRect(qrX, qrY, qrSize + 20, qrSize + 20, 12);
ctx.fill();
const qrCanvas = document.getElementById('poster-qrcode');
if (qrCanvas) {
ctx.drawImage(qrCanvas, qrX + 10, qrY + 10, qrSize, qrSize);
}
ctx.fillStyle = textColor;
ctx.font =
'14px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
ctx.fillText(t('扫码注册'), width / 2, qrY + qrSize + 55);
ctx.font =
'bold 18px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
ctx.fillText(`${t('邀请码')}: ${affCode}`, width / 2, qrY + qrSize + 85);
ctx.strokeStyle = 'rgba(255,255,255,0.3)';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(50, height - 80);
ctx.lineTo(width - 50, height - 80);
ctx.stroke();
ctx.fillStyle = 'rgba(255,255,255,0.8)';
ctx.font =
'12px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
ctx.fillText(
posterConfig?.footer_text || t('长按识别二维码,立即体验AI'),
width / 2,
height - 45,
);
},
[selectedTemplate, posterConfig, systemName, affCode, t],
);
// 绘制海报到 Canvas
const drawPoster = useCallback(() => {
const canvas = canvasRef.current;
if (!canvas || !affLink) return null;
const ctx = canvas.getContext('2d');
const width = 375;
const height = 667;
canvas.width = width * 2;
canvas.height = height * 2;
ctx.scale(2, 2);
const gradient = ctx.createLinearGradient(0, 0, width, height);
if (selectedTemplate.id === 'blue') {
gradient.addColorStop(0, '#667eea');
gradient.addColorStop(1, '#764ba2');
} else if (selectedTemplate.id === 'orange') {
gradient.addColorStop(0, '#f093fb');
gradient.addColorStop(1, '#f5576c');
} else if (selectedTemplate.id === 'green') {
gradient.addColorStop(0, '#4facfe');
gradient.addColorStop(1, '#00f2fe');
} else {
gradient.addColorStop(0, '#232526');
gradient.addColorStop(1, '#414345');
}
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, width, height);
drawContent(ctx, width, height);
return canvas;
}, [affLink, selectedTemplate, drawContent]);
// 下载海报
const handleDownload = async () => {
if (!affLink) {
showError(t('邀请链接获取中,请稍后'));
return;
}
setDownloading(true);
try {
await new Promise((resolve) => setTimeout(resolve, 100));
const canvas = drawPoster();
if (!canvas) {
showError(t('海报生成失败'));
return;
}
await new Promise((resolve) => setTimeout(resolve, 200));
const link = document.createElement('a');
link.download = `promotion-poster-${affCode}.png`;
link.href = canvas.toDataURL('image/png');
link.click();
showSuccess(t('海报下载成功'));
} catch (error) {
showError(t('下载失败: {{error}}', { error: error.message }));
} finally {
setDownloading(false);
}
};
// 复制并按实际结果提示(此前调用未处理结果,点击后无任何反馈)
const copyWithFeedback = async (text, name) => {
if (await copy(text)) {
showSuccess(t('已复制:{{name}}', { name }));
} else {
showError(t('复制失败,请手动复制'));
}
};
// 复制邀请链接
const handleCopyLink = async () => {
if (!affLink) {
showError(t('邀请链接获取中,请稍后'));
return;
}
copyWithFeedback(affLink, t('邀请链接'));
};
// 复制邀请码
const handleCopyCode = async () => {
if (!affCode) {
showError(t('邀请码获取中,请稍后'));
return;
}
copyWithFeedback(affCode, t('邀请码'));
};
const renderLinkMode = () => (
<div className='pm-link-layout'>
<section className='pm-invitation-card'>
<div className='pm-eyebrow'>{t('推广分享')}</div>
<Title level={4}>{systemName}</Title>
<Paragraph type='secondary'>
{posterConfig?.slogan || t('邀请好友,共享AI')}
</Paragraph>
<div className='pm-qrcode'>
<QRCodeCanvas
id='link-mode-qrcode'
value={affLink}
size={144}
level='M'
marginSize={2}
/>
</div>
<Text type='secondary'>{t('手机扫码注册')}</Text>
<div className='pm-benefits'>
<span>
<Gift size={14} aria-hidden />
{t('注册即送额度')}
</span>
<span>
<Users size={14} aria-hidden />
{t('消费返佣')}
</span>
</div>
</section>
<section className='pm-share-details'>
<div className='pm-field'>
<label htmlFor='promotion-link'>{t('邀请链接')}</label>
<Input id='promotion-link' value={affLink} readOnly size='large' />
<Button
type='primary'
icon={<ActionCopy size={16} aria-hidden />}
onClick={handleCopyLink}
>
{t('复制链接')}
</Button>
</div>
<div className='pm-field'>
<Text strong id='promotion-code-label'>
{t('邀请码')}
</Text>
<div
className='pm-code-row'
role='group'
aria-labelledby='promotion-code-label'
>
<Text id='promotion-code' className='pm-code'>
{affCode}
</Text>
<Button
icon={<ActionCopy size={16} aria-hidden />}
onClick={handleCopyCode}
>
{t('复制')}
</Button>
</div>
</div>
<Paragraph type='secondary' className='pm-share-hint'>
{t(
'将链接发送给好友,好友点击即可注册。支持微信、QQ、邮件等任意方式分享。',
)}
</Paragraph>
</section>
</div>
);
const renderPosterMode = () => (
<div className='pm-poster-layout'>
<div className='pm-preview-stage'>
<div
className='pm-poster'
style={{
'--pm-poster-background': selectedTemplate.bgGradient,
'--pm-poster-ink': selectedTemplate.textColor,
}}
>
<h2>{posterConfig?.slogan || t('邀请好友,共享AI')}</h2>
<p className='pm-poster-subtitle'>
{posterConfig?.sub_slogan || t('注册即可获得免费额度')}
</p>
<h3>{systemName}</h3>
<div className='pm-poster-qr'>
<QRCodeCanvas
id='poster-qrcode'
value={affLink}
size={130}
level='H'
marginSize={2}
/>
</div>
<p>{t('扫码注册')}</p>
<p className='pm-poster-code'>
{t('邀请码')}: {affCode}
</p>
<p className='pm-poster-footer'>
{posterConfig?.footer_text || t('长按识别二维码,立即体验AI')}
</p>
</div>
</div>
<section className='pm-poster-options'>
<div className='pm-field'>
<Text strong id='promotion-template-label'>
{t('选择模板')}
</Text>
<Radio.Group
className='pm-template-list'
aria-labelledby='promotion-template-label'
value={selectedTemplate.id}
onChange={(event) =>
setSelectedTemplate(
DEFAULT_TEMPLATES.find(
(item) => item.id === event.target.value,
),
)
}
>
{DEFAULT_TEMPLATES.map((template) => (
<Radio key={template.id} value={template.id}>
<span className='pm-template-label'>
<span
className='pm-template-swatch'
style={{ '--pm-template-background': template.bgGradient }}
/>
{t(template.name)}
</span>
</Radio>
))}
</Radio.Group>
</div>
<div className='pm-poster-actions'>
<Button
type='primary'
icon={<ActionDownload size={16} aria-hidden />}
onClick={handleDownload}
loading={downloading}
>
{t('下载海报')}
</Button>
<Button
icon={<ActionCopy size={16} aria-hidden />}
onClick={handleCopyLink}
>
{t('复制链接')}
</Button>
</div>
<Text type='secondary' className='pm-share-hint'>
{posterConfig?.footer_text || t('长按识别二维码,立即体验AI')}
</Text>
</section>
<canvas ref={canvasRef} hidden />
</div>
);
return (
<Modal
title={t('推广分享')}
open={visible}
onCancel={onClose}
footer={null}
width={800}
centered
className='promotion-modal'
>
{loading ? (
<div className='pm-loading' aria-label={t('加载中...')}>
<Skeleton active paragraph={{ rows: 7 }} />
</div>
) : (
<>
{affLink ? (
<Tabs
activeKey={activeTab}
onChange={setActiveTab}
className='promotion-tabs'
items={[
{
key: 'link',
label: (
<span className='pm-tab-label'>
<Monitor size={16} aria-hidden />
{t('链接分享')}
</span>
),
children: renderLinkMode(),
},
{
key: 'poster',
label: (
<span className='pm-tab-label'>
<Smartphone size={16} aria-hidden />
{t('海报分享')}
</span>
),
children: renderPosterMode(),
},
]}
/>
) : (
<Alert
type='warning'
showIcon
title={t('邀请链接获取中,请稍后')}
/>
)}
<button
type='button'
className='pm-rewards'
onClick={() => {
onClose();
navigate('/user-center/invite');
}}
>
<span className='pm-rewards-icon'>
<Gift size={20} aria-hidden />
</span>
<span className='pm-rewards-copy'>
<strong>{t('查看邀请奖励规则')}</strong>
<span>{t('了解返佣比例和奖励详情')}</span>
</span>
<ChevronRight size={18} aria-hidden />
</button>
</>
)}
</Modal>
);
};
export default PromotionPosterModal;