import * as XLSX from 'xlsx';

interface ExportColumn {
  key: string;
  title: string;
  width?: number;
}

export const exportService = {
  /**
   * 导出数据为 Excel 文件
   */
  exportToExcel<T extends Record<string, unknown>>(
    data: T[],
    columns: ExportColumn[],
    filename: string
  ): void {
    // 转换数据格式
    const exportData = data.map((item) => {
      const row: Record<string, unknown> = {};
      columns.forEach((col) => {
        row[col.title] = item[col.key];
      });
      return row;
    });

    // 创建工作簿
    const ws = XLSX.utils.json_to_sheet(exportData);

    // 设置列宽
    const colWidths = columns.map((col) => ({
      wch: col.width || 15,
    }));
    ws['!cols'] = colWidths;

    // 创建工作簿并添加工作表
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    // 导出文件
    XLSX.writeFile(wb, `${filename}.xlsx`);
  },

  /**
   * 导出数据为 CSV 文件
   */
  exportToCSV<T extends Record<string, unknown>>(
    data: T[],
    columns: ExportColumn[],
    filename: string
  ): void {
    // 转换数据格式
    const exportData = data.map((item) => {
      const row: Record<string, unknown> = {};
      columns.forEach((col) => {
        row[col.title] = item[col.key];
      });
      return row;
    });

    // 创建工作表
    const ws = XLSX.utils.json_to_sheet(exportData);

    // 转换为 CSV 字符串
    const csv = XLSX.utils.sheet_to_csv(ws);

    // 创建 Blob 并下载
    const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `${filename}.csv`;
    link.click();
    URL.revokeObjectURL(link.href);
  },

  /**
   * 下载文件
   */
  downloadFile(url: string, filename: string): void {
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    link.click();
  },
};
