const escapeCell = (value: string): string => {
  const normalized = value.replace(/"/g, '""').replace(/\r?\n/g, ' ');
  return `"${normalized}"`;
};

/**
 * 这里保留最小导出能力，优先满足 EMS 报表页在 Vue3 环境下可继续导出表格数据，
 * 避免因为旧版工具文件缺失导致整页无法启动。
 */
export const handleExport = (tableId: string, fileName: string, includeHidden = false): void => {
  const table = document.getElementById(tableId) as HTMLTableElement | null;
  if (!table) {
    return;
  }

  const rows = Array.from(table.querySelectorAll('tr')).map((row) => {
    const cells = Array.from(row.querySelectorAll<HTMLTableCellElement>('th,td')).filter((cell) => {
      if (includeHidden) {
        return true;
      }
      return cell.offsetParent !== null;
    });

    return cells.map((cell) => escapeCell(cell.innerText.trim())).join(',');
  });

  const csvContent = `\uFEFF${rows.join('\r\n')}`;
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);

  link.href = url;
  link.download = `${fileName}.csv`;
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};
