import axios from 'axios';
import { message } from 'antd';
import { API_CONFIG } from '../utils/config';

/**
 * 下载作品原图
 * @param {number} workId - 作品ID
 * @param {string} fileName - 保存的文件名
 */
export const downloadWork = async (workId, fileName = null) => {
  try {
    const token = localStorage.getItem('access_token');
    
    if (!token) {
      message.error('请先登录');
      return {
        success: false,
        message: '请先登录'
      };
    }

    // 使用 axios 下载文件
    const response = await axios({
      method: 'GET',
      url: `${API_CONFIG.baseURL}${API_CONFIG.apiPrefix}/works/${workId}/download`,
      headers: {
        'Authorization': `Bearer ${token}`
      },
      responseType: 'blob' // 重要：以 blob 形式接收
    });

    // 创建下载链接
    const blob = new Blob([response.data]);
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName || `work_${workId}.jpg`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    message.success('下载成功');
    return {
      success: true,
      message: '下载成功'
    };
  } catch (error) {
    if (error.response && error.response.status === 403) {
      const errorMessage = '您还未购买此作品，请先完成支付';
      message.error(errorMessage);
      return {
        success: false,
        message: errorMessage,
        needPurchase: true
      };
    }
    if (error.response && error.response.status === 401) {
      message.error('请先登录');
      return {
        success: false,
        message: '请先登录'
      };
    }
    const errorMessage = error.message || '下载失败';
    message.error(errorMessage);
    return {
      success: false,
      message: errorMessage
    };
  }
};
