use std::fmt::Display;
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use crate::column::ColumnDef;
use crate::value::CellValue;
use crate::write::{ExcelWriter, SheetOptions};
pub const XLSX_MIME: &str =
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
pub type ExportTaskFuture =
Pin<Box<dyn Future<Output = Result<ExportTaskOutput, String>> + Send + 'static>>;
#[derive(Debug, Clone)]
pub struct ExportTaskContext {
pub task_no: String,
pub query: serde_json::Value,
pub out_dir: PathBuf,
}
#[derive(Debug, Clone)]
pub struct ExportTaskOutput {
pub total_rows: i32,
pub file_name: String,
pub file_size: i64,
pub mime: Option<String>,
}
#[derive(Debug, Clone, Copy)]
pub enum ExportTaskKind {
Rows {
sheet_name: &'static str,
headers: &'static [&'static str],
},
File { mime: &'static str },
}
pub type ExportTaskFn = fn(ExportTaskContext) -> ExportTaskFuture;
pub struct ExportTaskEntry {
pub task_type: &'static str,
pub kind: ExportTaskKind,
pub run: ExportTaskFn,
}
inventory::collect!(ExportTaskEntry);
pub fn registered_export_tasks() -> Vec<&'static ExportTaskEntry> {
inventory::iter::<ExportTaskEntry>().collect()
}
pub fn export_task_entry(task_type: &str) -> Option<&'static ExportTaskEntry> {
inventory::iter::<ExportTaskEntry>()
.find(|e| e.task_type == task_type)
}
pub fn export_task_registered(task_type: &str) -> bool {
export_task_entry(task_type).is_some()
}
pub async fn run_export_task(
task_type: &str,
ctx: ExportTaskContext,
) -> Result<ExportTaskOutput, String> {
let entry = export_task_entry(task_type)
.ok_or_else(|| format!("导出类型「{task_type}」未注册"))?;
(entry.run)(ctx).await
}
pub async fn run_rows_task<F, Fut, E>(
ctx: ExportTaskContext,
task_type: &'static str,
sheet_name: &'static str,
headers: &'static [&'static str],
provider: F,
) -> Result<ExportTaskOutput, String>
where
F: FnOnce(ExportTaskContext) -> Fut + Send + 'static,
Fut: Future<Output = Result<Vec<Vec<String>>, E>> + Send + 'static,
E: Display,
{
let rows = provider(ctx.clone()).await.map_err(|e| e.to_string())?;
let total_rows = rows.len() as i32;
let file_name = format!("{}-{}.xlsx", ctx.task_no, task_type);
let path = ctx.out_dir.join(&file_name);
std::fs::create_dir_all(&ctx.out_dir)
.map_err(|e| format!("创建导出目录失败: {e}"))?;
let sheet = SheetOptions::new(sheet_name).columns(
headers
.iter()
.map(|h| ColumnDef::new(*h))
.collect::<Vec<_>>(),
);
let write_path = path.clone();
let file_size = tokio::task::spawn_blocking(move || -> Result<u64, String> {
let mut writer = ExcelWriter::new();
{
let mut ws = writer
.add_sheet(&sheet)
.map_err(|e| format!("创建工作表失败: {e}"))?;
ws.write_headers()
.map_err(|e| format!("写表头失败: {e}"))?;
for row in &rows {
let cells: Vec<CellValue> = row.iter().map(|v| CellValue::Text(v.clone())).collect();
ws.write_row(&cells)
.map_err(|e| format!("写数据行失败: {e}"))?;
}
ws.finish().map_err(|e| format!("收尾工作表失败: {e}"))?;
}
writer
.save(&write_path)
.map_err(|e| format!("保存导出文件失败: {e}"))
})
.await
.map_err(|e| format!("导出写入线程异常: {e}"))??;
Ok(ExportTaskOutput {
total_rows,
file_name,
file_size: file_size as i64,
mime: Some(XLSX_MIME.to_string()),
})
}
pub async fn run_file_task<F, Fut, E>(
ctx: ExportTaskContext,
mime: &'static str,
provider: F,
) -> Result<ExportTaskOutput, String>
where
F: FnOnce(ExportTaskContext) -> Fut + Send + 'static,
Fut: Future<Output = Result<(i64, String), E>> + Send + 'static,
E: Display,
{
let (total_rows, file_name) = provider(ctx.clone()).await.map_err(|e| e.to_string())?;
let file_size = std::fs::metadata(ctx.out_dir.join(&file_name))
.map_err(|e| format!("读取导出文件大小失败: {e}"))?
.len();
Ok(ExportTaskOutput {
total_rows: total_rows as i32,
file_name,
file_size: file_size as i64,
mime: Some(mime.to_string()),
})
}