import request from "@/utils/request"; // 使用导入的 request 函数进行网络请求 export const table = (params: { table: string }) => { return request({ url: "/admin/table", method: "GET", 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: "/admin/update_item", method: "PUT", data: data, }); }; // 提交新增数据 export const addItem = (data: { table: string, item: any }) => { return customRequest({ url: "/admin/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: "/admin/delete_item", method: "POST", data: { table: params.table, condition: conditionString, }, }); }; // 下载模板 export const downloadTemplate = (table: string, format: string = 'xlsx') => { return customRequest({ url: "/admin/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: "/admin/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: "/admin/import_data", method: "POST", data: formData, headers: { 'Content-Type': 'multipart/form-data', }, }); };