fast-excel 1.0.0

通用 Excel 导入导出工具:流式读写(百万级)、动态表头适配、多 sheet、单元格图片、批量落库(纯 Rust,对标 EasyExcel)
Documentation
//! 内置函数方法:在列值表达式(闭包)里直接调用
//!
//! 本模块不引入任何表达式解析引擎——「表达式」就是业务侧写的 Rust 闭包,
//! 这里只是把常用的文本 / 金额 / 日期 / 兜底 / 序号计算封装成可直接调用的方法,
//! 让闭包保持一行、可读。
//!
//! ```ignore
//! use fast_excel::funcs;
//! use fast_excel::{CellValue, SheetOptions, ColumnDef};
//!
//! let sheet = SheetOptions::new("明细")
//!     .columns(ProductRow::columns())
//!     .computed(ColumnDef::new("全名"), |row| {
//!         CellValue::Text(funcs::concat(&[&row.text("姓"), &row.text("名")]))
//!     })
//!     .computed(ColumnDef::new("导出时间"), |_row| {
//!         CellValue::Text(funcs::date_fmt(funcs::today(), "%Y-%m-%d"))
//!     });
//! ```

use std::sync::Arc;
use std::sync::atomic::{AtomicI64, Ordering};

use chrono::{Datelike, NaiveDate, NaiveDateTime, Timelike};
use rust_decimal::{Decimal, RoundingStrategy};

use crate::value::CellValue;

// ───────────────────────────── 文本 ─────────────────────────────

/// 拼接多段文本:`concat(&["A", "-", "B"])` → `A-B`
pub fn concat(parts: &[&str]) -> String {
    parts.concat()
}

/// 用分隔符拼接:`join("-", &["A", "B"])` → `A-B`
pub fn join(sep: &str, parts: &[&str]) -> String {
    parts.join(sep)
}

/// 转大写
pub fn upper(s: &str) -> String {
    s.to_uppercase()
}

/// 转小写
pub fn lower(s: &str) -> String {
    s.to_lowercase()
}

/// 去首尾空白
pub fn trim(s: &str) -> String {
    s.trim().to_string()
}

/// 全部替换
pub fn replace_all(s: &str, from: &str, to: &str) -> String {
    s.replace(from, to)
}

/// 按字符截取(`start` 从 0 开始,`len` 为字符数)
pub fn substr(s: &str, start: usize, len: usize) -> String {
    s.chars().skip(start).take(len).collect()
}

/// 左侧补字符到指定宽度(如编号补零):`pad_left("7", 4, '0')` → `0007`
pub fn pad_left(s: &str, width: usize, fill: char) -> String {
    let n = s.chars().count();
    if n >= width {
        return s.to_string();
    }
    let mut out = String::with_capacity(width);
    out.extend(std::iter::repeat(fill).take(width - n));
    out.push_str(s);
    out
}

// ───────────────────────────── 数值 / 金额 ─────────────────────────────

/// 金额四舍五入到 2 位小数的纯数字串(写数值单元格用)
pub fn money(v: Decimal) -> String {
    v.round_dp_with_strategy(2, RoundingStrategy::MidpointAwayFromZero)
        .normalize()
        .to_string()
}

/// 金额两位小数(保留两位、不带千分位):`12.5` → `12.50`
pub fn money_fixed(v: Decimal) -> String {
    format!("{:.2}", v.round_dp_with_strategy(2, RoundingStrategy::MidpointAwayFromZero))
}

/// 百分号文本:`percent(0.1234, 1)` → `12.3%`
pub fn percent(v: f64, scale: u32) -> String {
    format!("{:.*}%", scale as usize, v * 100.0)
}

/// 四舍五入到指定小数位
pub fn round(v: f64, scale: u32) -> f64 {
    let f = 10f64.powi(scale as i32);
    (v * f).round() / f
}

// ───────────────────────────── 日期时间 ─────────────────────────────

/// 今天(本地时区)
pub fn today() -> NaiveDate {
    chrono::Local::now().date_naive()
}

/// 当前时间(本地时区)
pub fn now() -> NaiveDateTime {
    chrono::Local::now().naive_local()
}

/// 按 `chrono` 格式串格式化日期:`date_fmt(d, "%Y/%m/%d")`
pub fn date_fmt(d: NaiveDate, fmt: &str) -> String {
    d.format(fmt).to_string()
}

/// 按 `chrono` 格式串格式化日期时间
pub fn datetime_fmt(dt: NaiveDateTime, fmt: &str) -> String {
    dt.format(fmt).to_string()
}

/// 当前年月日打包成数字(如 20251004),适合做编号前缀
pub fn ymd(d: NaiveDate) -> i64 {
    (d.year() as i64) * 10_000 + (d.month() as i64) * 100 + d.day() as i64
}

/// 当天的秒数(0..86399),适合做时间戳后缀
pub fn seconds_of_day(dt: NaiveDateTime) -> i64 {
    dt.hour() as i64 * 3600 + dt.minute() as i64 * 60 + dt.second() as i64
}

// ───────────────────────────── 值 / 兜底 ─────────────────────────────

/// 任意可转值 → 单元格值(`text("A")` / `text(12)` / `text(1.5)`)
pub fn text(v: impl Into<CellValue>) -> CellValue {
    v.into()
}

/// 取第一个非空值,全空返回 `Empty`
pub fn coalesce(values: &[CellValue]) -> CellValue {
    values
        .iter()
        .find(|v| !v.is_empty())
        .cloned()
        .unwrap_or(CellValue::Empty)
}

/// 空值兜底:`if_empty(v, fallback)`
pub fn if_empty(v: CellValue, fallback: CellValue) -> CellValue {
    if v.is_empty() { fallback } else { v }
}

/// 字典映射(如状态码 → 名称):命中返回映射值,未命中保留原值
pub fn map_dict(v: &CellValue, pairs: &[(&str, &str)]) -> CellValue {
    let key = v.to_text();
    let key = key.trim();
    match pairs.iter().find(|(from, _)| *from == key) {
        Some((_, to)) => CellValue::Text((*to).to_string()),
        None => v.clone(),
    }
}

// ───────────────────────────── 序号 ─────────────────────────────

/// 自增序号(`Clone` 共享同一计数,可跨并发导出任务使用)
#[derive(Clone, Debug)]
pub struct Seq {
    n: Arc<AtomicI64>,
    step: i64,
}

impl Seq {
    pub fn new(start: i64, step: i64) -> Self {
        Self {
            n: Arc::new(AtomicI64::new(start)),
            step: if step == 0 { 1 } else { step },
        }
    }

    /// 取下一个值并自增
    pub fn next(&self) -> i64 {
        self.n.fetch_add(self.step, Ordering::Relaxed)
    }

    /// 取下一个值并自增(直接当单元格值用)
    pub fn next_cell(&self) -> CellValue {
        CellValue::Number(self.next() as f64)
    }

    /// 当前值(不递增)
    pub fn current(&self) -> i64 {
        self.n.load(Ordering::Relaxed)
    }
}

/// 创建自增序号:`seq(1, 1)` → 1,2,3…
pub fn seq(start: i64, step: i64) -> Seq {
    Seq::new(start, step)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_text_helpers() {
        assert_eq!(concat(&["A", "-", "B"]), "A-B");
        assert_eq!(join("/", &["x", "y"]), "x/y");
        assert_eq!(upper("ab"), "AB");
        assert_eq!(substr("abcdef", 1, 3), "bcd");
        assert_eq!(pad_left("7", 4, '0'), "0007");
        assert_eq!(replace_all("a-b-c", "-", "_"), "a_b_c");
    }

    #[test]
    fn test_value_helpers() {
        let v = coalesce(&[CellValue::Empty, CellValue::Text("x".into())]);
        assert_eq!(v.to_text(), "x");
        assert_eq!(
            if_empty(CellValue::Empty, CellValue::Number(1.0)).to_text(),
            "1"
        );
        let mapped = map_dict(&CellValue::Text("1".into()), &[("1", "启用")]);
        assert_eq!(mapped.to_text(), "启用");
    }

    #[test]
    fn test_seq() {
        let s = seq(10, 2);
        assert_eq!(s.next(), 10);
        assert_eq!(s.next(), 12);
        assert_eq!(s.current(), 14);
    }

    #[test]
    fn test_money_and_round() {
        assert_eq!(money(Decimal::new(125, 1)), "12.5");
        assert_eq!(money_fixed(Decimal::new(125, 1)), "12.50");
        assert_eq!(round(1.2345, 2), 1.23);
        assert_eq!(percent(0.1234, 1), "12.3%");
    }
}