1use std::fmt::Display;
10use std::future::Future;
11use std::path::PathBuf;
12use std::pin::Pin;
13
14use crate::column::ColumnDef;
15use crate::value::CellValue;
16use crate::write::{ExcelWriter, SheetOptions};
17
18pub const XLSX_MIME: &str =
20 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
21
22pub type ExportTaskFuture =
24 Pin<Box<dyn Future<Output = Result<ExportTaskOutput, String>> + Send + 'static>>;
25
26#[derive(Debug, Clone)]
28pub struct ExportTaskContext {
29 pub task_no: String,
31 pub query: serde_json::Value,
33 pub out_dir: PathBuf,
35}
36
37#[derive(Debug, Clone)]
39pub struct ExportTaskOutput {
40 pub total_rows: i32,
42 pub file_name: String,
44 pub file_size: i64,
45 pub mime: Option<String>,
47}
48
49#[derive(Debug, Clone, Copy)]
51pub enum ExportTaskKind {
52 Rows {
54 sheet_name: &'static str,
55 headers: &'static [&'static str],
56 },
57 File { mime: &'static str },
59}
60
61pub type ExportTaskFn = fn(ExportTaskContext) -> ExportTaskFuture;
63
64pub struct ExportTaskEntry {
66 pub task_type: &'static str,
67 pub kind: ExportTaskKind,
68 pub run: ExportTaskFn,
69}
70
71inventory::collect!(ExportTaskEntry);
72
73pub fn registered_export_tasks() -> Vec<&'static ExportTaskEntry> {
75 inventory::iter::<ExportTaskEntry>().collect()
76}
77
78pub fn export_task_entry(task_type: &str) -> Option<&'static ExportTaskEntry> {
80 inventory::iter::<ExportTaskEntry>()
81 .find(|e| e.task_type == task_type)
82}
83
84pub fn export_task_registered(task_type: &str) -> bool {
86 export_task_entry(task_type).is_some()
87}
88
89pub async fn run_export_task(
91 task_type: &str,
92 ctx: ExportTaskContext,
93) -> Result<ExportTaskOutput, String> {
94 let entry = export_task_entry(task_type)
95 .ok_or_else(|| format!("导出类型「{task_type}」未注册"))?;
96 (entry.run)(ctx).await
97}
98
99pub async fn run_rows_task<F, Fut, E>(
103 ctx: ExportTaskContext,
104 task_type: &'static str,
105 sheet_name: &'static str,
106 headers: &'static [&'static str],
107 provider: F,
108) -> Result<ExportTaskOutput, String>
109where
110 F: FnOnce(ExportTaskContext) -> Fut + Send + 'static,
111 Fut: Future<Output = Result<Vec<Vec<String>>, E>> + Send + 'static,
112 E: Display,
113{
114 let rows = provider(ctx.clone()).await.map_err(|e| e.to_string())?;
115 let total_rows = rows.len() as i32;
116 let file_name = format!("{}-{}.xlsx", ctx.task_no, task_type);
117 let path = ctx.out_dir.join(&file_name);
118 std::fs::create_dir_all(&ctx.out_dir)
119 .map_err(|e| format!("创建导出目录失败: {e}"))?;
120
121 let sheet = SheetOptions::new(sheet_name).columns(
123 headers
124 .iter()
125 .map(|h| ColumnDef::new(*h))
126 .collect::<Vec<_>>(),
127 );
128 let write_path = path.clone();
129 let file_size = tokio::task::spawn_blocking(move || -> Result<u64, String> {
130 let mut writer = ExcelWriter::new();
131 {
132 let mut ws = writer
133 .add_sheet(&sheet)
134 .map_err(|e| format!("创建工作表失败: {e}"))?;
135 ws.write_headers()
136 .map_err(|e| format!("写表头失败: {e}"))?;
137 for row in &rows {
138 let cells: Vec<CellValue> = row.iter().map(|v| CellValue::Text(v.clone())).collect();
139 ws.write_row(&cells)
140 .map_err(|e| format!("写数据行失败: {e}"))?;
141 }
142 ws.finish().map_err(|e| format!("收尾工作表失败: {e}"))?;
143 }
144 writer
145 .save(&write_path)
146 .map_err(|e| format!("保存导出文件失败: {e}"))
147 })
148 .await
149 .map_err(|e| format!("导出写入线程异常: {e}"))??;
150
151 Ok(ExportTaskOutput {
152 total_rows,
153 file_name,
154 file_size: file_size as i64,
155 mime: Some(XLSX_MIME.to_string()),
156 })
157}
158
159pub async fn run_file_task<F, Fut, E>(
161 ctx: ExportTaskContext,
162 mime: &'static str,
163 provider: F,
164) -> Result<ExportTaskOutput, String>
165where
166 F: FnOnce(ExportTaskContext) -> Fut + Send + 'static,
167 Fut: Future<Output = Result<(i64, String), E>> + Send + 'static,
168 E: Display,
169{
170 let (total_rows, file_name) = provider(ctx.clone()).await.map_err(|e| e.to_string())?;
171 let file_size = std::fs::metadata(ctx.out_dir.join(&file_name))
172 .map_err(|e| format!("读取导出文件大小失败: {e}"))?
173 .len();
174 Ok(ExportTaskOutput {
175 total_rows: total_rows as i32,
176 file_name,
177 file_size: file_size as i64,
178 mime: Some(mime.to_string()),
179 })
180}