import { ToastService } from '@/dialog';
import { t } from '@/locales';
export const copyText = async (text: string): Promise<boolean> => {
if (!text) return false;
try {
// 优先使用 Clipboard API
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
showSuccess();
return true;
}
// 降级方案
const result = await fallbackCopyText(text);
if (result) {
showSuccess();
return true;
} else {
showError();
return false;
}
} catch (err) {
showError();
return false;
}
};
// 降级复制方案
const fallbackCopyText = async (text: string): Promise<boolean> => {
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.cssText = 'position:fixed;left:-999999px;top:-999999px;';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
const success = document.execCommand('copy');
textArea.remove();
return success;
} catch (err) {
textArea.remove();
return false;
}
};
// 显示成功提示
const showSuccess = () => {
ToastService.show(t('bank.point.order_info.copy_success'));
};
// 显示错误提示
const showError = () => {
ToastService.show(t('bank.point.order_info.copy_fail'), 'error');
};