1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#[derive(Clone, Debug)]
pub enum OrderType {
    Asc,
    Desc,
    None,
}

impl OrderType {
    pub fn sql(&self) -> String {
        match self {
            OrderType::Asc => "asc".to_string(),
            OrderType::Desc => "desc".to_string(),
            OrderType::None => "".to_string(),
        }
    }
}

#[derive(Clone, Debug)]
pub struct Order {
    pub field: String,
    pub order_type: OrderType,
}

impl Order {
    /// 字段升序
    pub fn asc(field: String) -> Self {
        Self {
            field,
            order_type: OrderType::Asc,
        }
    }
    /// 字段降序
    pub fn desc(field: String) -> Self {
        Self {
            field,
            order_type: OrderType::Desc,
        }
    }
    /// 字段默认顺序
    pub fn new(field: String) -> Self {
        Self {
            field,
            order_type: OrderType::None,
        }
    }
}

pub struct PageRequest {
    /// 每页记录数
    page_size: usize,
    /// 页码,从 1 开始
    page_no: usize,
    /// 是否统计页面信息: 总记录数,总页数
    pub total_page_info: bool,
}

impl PageRequest {
    pub fn new(page_size: usize, page_no: usize) -> Self {
        Self {
            page_no,
            page_size,
            total_page_info: false,
        }
    }

    pub fn with_total(page_size: usize, page_no: usize) -> Self {
        Self {
            page_no,
            page_size,
            total_page_info: true,
        }
    }

    pub fn get_page_no(&self) -> usize {
        if self.page_no <= 0 {
            1
        } else {
            self.page_no
        }
    }

    pub fn get_page_size(&self) -> usize {
        if self.page_size <= 0 {
            20
        } else {
            self.page_size
        }
    }
}

#[derive(Default)]
pub struct PageResult<O>
where
    O: std::marker::Send,
    O: Unpin,
{
    /// 每页记录数
    pub page_size: usize,
    /// 页码,从 1 开始
    pub page_no: usize,
    /// 总记录数
    pub total: usize,
    /// 总页数
    pub page_count: usize,
    /// 记录
    pub records: Vec<O>,
}

impl<O> PageResult<O>
where
    O: std::marker::Send,
    O: Unpin,
{
    /// 设置总记录数,同时计算总页数
    pub fn set_total(&mut self, total: usize) {
        self.total = total;
        if total == 0 {
            self.page_count = 0;
        } else {
            let page_count = total / self.page_size;
            if total % self.page_size != 0 {
                self.page_count = page_count + 1;
            } else {
                self.page_count = page_count
            }
        }
    }
}