import { Toast } from '../toast';

import type { ICopyText } from './types';


/**
 * 复制到剪切板
 * @param text 待复制的文本
 * @param showToast 复制成功是否弹提示，默认true弹"内容已复制"
 */
const copyText: ICopyText = function (text: string, showToast = true) {
  return new Promise((resolve, reject) => {
    const pasteText = document.getElementById('#clipboard');
    pasteText?.remove();
    const textarea = document.createElement('textarea');
    textarea.id = '#clipboard';
    textarea.style.position = 'fixed';
    textarea.style.top = '-9999px';
    textarea.style.zIndex = '-9999';
    document.body.appendChild(textarea);
    textarea.value = text;
    textarea.select();
    textarea.setSelectionRange(0, textarea.value.length);
    const result = document.execCommand('Copy', false);
    textarea.blur();
    if (result) {
      if (showToast) {
        Toast.show('内容已复制');
      }
      resolve();
    } else {
      reject();
    }
  });
};

export { copyText };
