/*
 * 下载封装：统一 token 注入与错误处理
 */

import axios from 'axios';

export interface DownloadParams {
  path: string;
  params?: any;
}

export async function downloadExcel({ path, params }: DownloadParams) {
  try {
    const userData = localStorage.getItem('userData');
    const { token = '' } = userData ? JSON.parse(userData) : { token: '' };
    const url = `/gateway${path}`;

    const response = await axios({
      method: 'get',
      url,
      responseType: 'blob',
      headers: { token },
      params,
    });

    const filename = decodeURI(
      response.headers['content-disposition'] || 'download.xlsx',
    );
    const objectUrl = URL.createObjectURL(
      new Blob([response.data], { type: 'application/vnd.ms-excel' }),
    );
    const link = document.createElement('a');
    link.download = `${filename}`;
    link.style.display = 'none';
    link.href = objectUrl;
    link.click();
    document.body.appendChild(link);
  } catch (err) {
    // 统一在调用方做 message.error，避免此处直接耦合 UI
    throw err;
  }
}
