import request from "@/utils/request";

// 使用导入的 request 函数进行网络请求
export const table = (params: { table: string }) => {
  return request({
    url: "/table",
    method: "POST",
    data: params,
  });
};

const customRequest = (options: any) => {
  return request(options)
    .then(response => response.data)
    .catch(error => {
      if (error.response && error.response.status === 409) {
        console.error('数据重复:', error.response.data);
        throw new Error('数据重复，请重新添加');
      } else {
        console.error(`请求失败: ${error.message || '未知错误'}`);
        throw new Error(`请求失败: ${error.message || '未知错误'}`);
      }
    });
};

export const updateItem = (data: { table: string, item: any }) => {
  return customRequest({
    url: "/update_item",
    method: "PUT",
    data: data,
  });
};

export const addItem = (data: { table: string, item: any }) => {
  return customRequest({
    url: "/add_item",
    method: "POST",
    data: data,
  }).catch(error => {
    if (error.message.includes("数据重复")) {
      alert(error.message); 
    }
    throw error; 
  });
};

export const deleteItemApi = (params: { table: string; condition: any }) => {
  const conditionString = `${Object.keys(params.condition)[0]}=${params.condition[Object.keys(params.condition)[0]]}`;
  return customRequest({
    url: "/delete_item",
    method: "POST",
    data: {
      table: params.table,
      condition: conditionString,
    },
  });
};

export const downloadTemplate = (table: string, format: string = 'xlsx') => {
  return customRequest({
    url: "/download_template",
    method: "GET",
    params: { table, format },
    responseType: 'blob',
  }).then(response => {
    const blob = new Blob([response], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `${table}_template.${format}`;
    link.click();
    window.URL.revokeObjectURL(url);
  });
};

export const exportData = (table: string, format: string = 'excel') => {
  const backendFormat = format.toLowerCase() === 'xlsx' ? 'excel' : format;

  return customRequest({
    url: "/export_data",
    method: "GET",
    params: { table, format: backendFormat },
    responseType: 'blob',
  }).then(response => {
    const blob = new Blob([response], {
      type: backendFormat === 'excel' 
        ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
        : 'text/csv',
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `${table}_data.${backendFormat === 'excel' ? 'xlsx' : 'csv'}`;
    link.click();
    window.URL.revokeObjectURL(url);
  }).catch(error => {
    console.error('导出数据时发生错误:', error);
    throw error;
  });
};

export const importData = (table: string, file: File) => {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('table', table);
  return customRequest({
    url: "/import_data",
    method: "POST",
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
};