import React, { useState, useCallback, useEffect, useRef } from 'react'; import { motion } from 'framer-motion'; import { Share2, Copy, Check, X, AlertTriangle, Building2 } from 'lucide-react'; import { useResponsive } from '../../hooks/useResponsive'; import { encryptShareParamsSync } from '../../utils/shareCrypto'; import { supabase } from '../../supabase/client'; interface ShareModalProps { isOpen: boolean; onClose: () => void; planId: string; factoryType: 'textile' | 'washing'; factoryName?: string; } export function ShareModal({ isOpen, onClose, planId, factoryType, factoryName }: ShareModalProps) { const { isMobile } = useResponsive(); const [copied, setCopied] = useState(false); const [showConfirm, setShowConfirm] = useState(false); const [recipientCompany, setRecipientCompany] = useState(''); const [confirmFactoryName, setConfirmFactoryName] = useState(''); const [confirmCompanyName, setConfirmCompanyName] = useState(''); const [error, setError] = useState(''); const [shortCode, setShortCode] = useState(''); const shortLinkGenerated = useRef(false); // 获取当前用户的公司名称 useEffect(() => { const fetchCompanyName = async () => { const { data: { user } } = await supabase.auth.getUser(); if (user) { const { data: profile } = await supabase .from('profiles') .select('company_id') .eq('id', user.id) .single(); if (profile?.company_id) { const { data: company } = await supabase .from('companies') .select('name') .eq('id', profile.company_id) .single(); if (company) { setRecipientCompany(company.name); } } } }; if (isOpen) { fetchCompanyName(); // 生成短链 if (!shortLinkGenerated.current) { shortLinkGenerated.current = true; generateShortLink(); } } else { // 弹窗关闭时重置 shortLinkGenerated.current = false; setShortCode(''); } }, [isOpen]); // 生成短链 const generateShortLink = useCallback(async () => { const baseUrl = window.location.origin + window.location.pathname; // 生成短码(6位随机字符) const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let code = ''; for (let i = 0; i < 6; i++) { code += chars.charAt(Math.floor(Math.random() * chars.length)); } // 保存到数据库 const { data: { user } } = await supabase.auth.getUser(); if (user) { const { error } = await supabase.from('share_links').insert({ short_code: code, plan_id: planId, factory_type: factoryType, created_by: user.id, expires_at: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString() // 7天过期 }); if (!error) { setShortCode(code); console.log('短链生成成功:', code); } else { console.error('短链保存失败:', error); } } else { console.error('用户未登录,无法生成短链'); } }, [planId, factoryType]); // 生成分享链接 const generateShareLink = useCallback(() => { const baseUrl = window.location.origin + window.location.pathname; if (shortCode) { return `${baseUrl}#/import?s=${shortCode}`; } // 如果短链还未生成,使用长链接 const token = encryptShareParamsSync(planId, factoryType); return `${baseUrl}#/import?token=${token}`; }, [planId, factoryType, shortCode]); const handleCopy = useCallback(async () => { const link = generateShareLink(); try { await navigator.clipboard.writeText(link); setCopied(true); setTimeout(() => setCopied(false), 2000); } catch { const textarea = document.createElement('textarea'); textarea.value = link; document.body.appendChild(textarea); textarea.select(); document.execCommand('copy'); document.body.removeChild(textarea); setCopied(true); setTimeout(() => setCopied(false), 2000); } }, [generateShareLink]); const handleConfirmShare = () => { setError(''); if (confirmFactoryName.trim() !== factoryName?.trim()) { setError('工厂名称不匹配,请确认工厂名称'); return; } if (confirmCompanyName.trim() !== recipientCompany.trim()) { setError('对方公司名称不匹配,请确认对方公司名称'); return; } // 验证通过,显示分享链接 setShowConfirm(false); }; const resetConfirm = () => { setShowConfirm(false); setConfirmFactoryName(''); setConfirmCompanyName(''); setError(''); }; if (!isOpen) return null; const link = generateShareLink(); const factoryLabel = factoryType === 'textile' ? '织布厂' : '水洗厂'; return (
{!showConfirm ? ( <>

分享链接

发送给{factoryLabel}

{link}

) : ( <>

二次确认

请确认分享信息

目标工厂

{factoryName || '未指定'}

您的公司

{recipientCompany || '加载中...'}

setConfirmFactoryName(e.target.value)} placeholder="输入工厂名称" className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500" />
setConfirmCompanyName(e.target.value)} placeholder="输入对方公司名称" className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500" />
{error && (

{error}

)}
)}
); }