"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.download = exports.copyToClipboard = exports.copyToClipboardByClipboard = exports.copyToClipboardByExecCommand = void 0;
const lodash_1 = require("lodash");
const export_1 = require("../../common/interface/export");
/**
 * 同步复制
 */
const copyToClipboardByExecCommand = (data) => new Promise((resolve, reject) => {
    let content;
    if (Array.isArray(data)) {
        content = (0, lodash_1.get)(data.filter((item) => item.type === export_1.CopyMIMEType.PLAIN), '[0].content', '');
    }
    else {
        content = data.content || '';
    }
    const textarea = document.createElement('textarea');
    textarea.value = content;
    document.body.appendChild(textarea);
    // 开启 preventScroll, 防止页面有滚动条时触发滚动
    textarea.focus({ preventScroll: true });
    textarea.select();
    const success = document.execCommand('copy');
    document.body.removeChild(textarea);
    if (success) {
        resolve();
    }
    else {
        reject();
    }
});
exports.copyToClipboardByExecCommand = copyToClipboardByExecCommand;
/**
 * 异步复制
 */
const copyToClipboardByClipboard = (data) => navigator.clipboard
    .write([
    new ClipboardItem((0, lodash_1.concat)(data).reduce((prev, copyable) => {
        const { type, content } = copyable;
        // eslint-disable-next-line no-control-regex
        const contentToCopy = content.replace(/\x00/g, '');
        return Object.assign(Object.assign({}, prev), { [type]: new Blob([contentToCopy], { type }) });
    }, {})),
])
    .catch(() => (0, exports.copyToClipboardByExecCommand)(data));
exports.copyToClipboardByClipboard = copyToClipboardByClipboard;
/**
 * @name 复制数据
 * @param data 数据源
 * @param async 异步复制
 */
const copyToClipboard = (data, async = true) => {
    let copyableItem;
    if (typeof data === 'string') {
        copyableItem = {
            content: data,
            type: export_1.CopyMIMEType.PLAIN,
        };
    }
    else {
        copyableItem = data;
    }
    if (!navigator.clipboard || !window.ClipboardItem || !async) {
        return (0, exports.copyToClipboardByExecCommand)(copyableItem);
    }
    return (0, exports.copyToClipboardByClipboard)(copyableItem);
};
exports.copyToClipboard = copyToClipboard;
/**
 * @name 导出数据
 * @param dataString 数据源 (字符串)
 * @param fileName 文件名 (格式为 csv)
 */
const download = (dataString, fileName) => {
    try {
        const link = document.createElement('a');
        link.download = `${fileName}.csv`;
        // Avoid errors in Chinese encoding.
        const dataBlob = new Blob([`\ufeff${dataString}`], {
            type: 'text/csv;charset=utf-8',
        });
        link.href = URL.createObjectURL(dataBlob);
        link.click();
        URL.revokeObjectURL(link.href);
    }
    catch (error) {
        // eslint-disable-next-line no-console
        console.error(error);
    }
};
exports.download = download;
//# sourceMappingURL=utils.js.map