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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
use super::canvas;
use super::color::*;
use super::common::*;
use super::component::*;
use super::params::*;
use super::theme::{get_default_theme, get_theme, Theme, DEFAULT_Y_AXIS_WIDTH};
use super::util::*;
use super::Canvas;
use super::Chart;
use crate::charts::measure_text_width_family;
use charts_rs_derive::Chart;

#[derive(Clone, Debug, Default, Chart)]
pub struct PieChart {
    pub width: f32,
    pub height: f32,
    pub x: f32,
    pub y: f32,
    pub margin: Box,
    pub series_list: Vec<Series>,
    pub font_family: String,
    pub background_color: Color,
    pub is_light: bool,

    // title
    pub title_text: String,
    pub title_font_size: f32,
    pub title_font_color: Color,
    pub title_font_weight: Option<String>,
    pub title_margin: Option<Box>,
    pub title_align: Align,
    pub title_height: f32,

    // sub title
    pub sub_title_text: String,
    pub sub_title_font_size: f32,
    pub sub_title_font_color: Color,
    pub sub_title_font_weight: Option<String>,
    pub sub_title_margin: Option<Box>,
    pub sub_title_align: Align,
    pub sub_title_height: f32,

    // legend
    pub legend_font_size: f32,
    pub legend_font_color: Color,
    pub legend_font_weight: Option<String>,
    pub legend_align: Align,
    pub legend_margin: Option<Box>,
    pub legend_category: LegendCategory,
    pub legend_show: Option<bool>,

    pub radius: f32,
    pub inner_radius: f32,
    pub rose_type: Option<bool>,
    pub border_radius: Option<f32>,

    // x axis
    pub x_axis_data: Vec<String>,
    pub x_axis_height: f32,
    pub x_axis_stroke_color: Color,
    pub x_axis_font_size: f32,
    pub x_axis_font_color: Color,
    pub x_axis_font_weight: Option<String>,
    pub x_axis_name_gap: f32,
    pub x_axis_name_rotate: f32,
    pub x_axis_margin: Option<Box>,
    pub x_boundary_gap: Option<bool>,

    // y axis
    pub y_axis_configs: Vec<YAxisConfig>,

    // grid
    pub grid_stroke_color: Color,
    pub grid_stroke_width: f32,

    // series
    pub series_stroke_width: f32,
    pub series_label_font_color: Color,
    pub series_label_font_size: f32,
    pub series_label_font_weight: Option<String>,
    pub series_label_formatter: String,
    pub series_colors: Vec<Color>,
    pub series_symbol: Option<Symbol>,
    pub series_smooth: bool,
    pub series_fill: bool,
}

impl PieChart {
    fn fill_default(&mut self) {
        self.radius = 150.0;
        self.inner_radius = 40.0;
        self.legend_show = Some(false);
        self.rose_type = Some(true);
    }
    /// Creates a pie chart from json.
    pub fn from_json(data: &str) -> canvas::Result<PieChart> {
        let mut p = PieChart {
            ..Default::default()
        };
        p.fill_default();
        let value = p.fill_option(data)?;
        if let Some(radius) = get_f32_from_value(&value, "radius") {
            p.radius = radius;
        }
        if let Some(inner_radius) = get_f32_from_value(&value, "inner_radius") {
            p.inner_radius = inner_radius;
        }
        if let Some(rose_type) = get_bool_from_value(&value, "rose_type") {
            p.rose_type = Some(rose_type);
        }
        if let Some(border_radius) = get_f32_from_value(&value, "border_radius") {
            p.border_radius = Some(border_radius);
        }
        Ok(p)
    }
    /// Creates a pie chart with custom theme.
    pub fn new_with_theme(series_list: Vec<Series>, theme: &str) -> PieChart {
        let mut p = PieChart {
            series_list,
            ..Default::default()
        };
        p.fill_default();
        p.fill_theme(get_theme(theme));
        p
    }
    /// Creates a pie chart with default theme.
    pub fn new(series_list: Vec<Series>) -> PieChart {
        PieChart::new_with_theme(series_list, &get_default_theme())
    }
    /// Converts pie chart to svg.
    pub fn svg(&self) -> canvas::Result<String> {
        let mut c = Canvas::new_width_xy(self.width, self.height, self.x, self.y);

        self.render_background(c.child(Box::default()));
        c.margin = self.margin.clone();

        let title_height = self.render_title(c.child(Box::default()));

        let legend_height = self.render_legend(c.child(Box::default()));
        // title 与 legend 取较高的值
        let axis_top = if legend_height > title_height {
            legend_height
        } else {
            title_height
        };
        if axis_top > 0.0 {
            c = c.child(Box {
                top: axis_top,
                ..Default::default()
            });
        }

        let values: Vec<f32> = self
            .series_list
            .iter()
            .map(|item| item.data.iter().sum())
            .collect();
        let mut max = 0.0;
        let mut sum = 0.0;
        for item in values.iter() {
            sum += *item;
            if *item > max {
                max = *item;
            }
        }
        let mut delta = 360.0 / values.len() as f32;
        let mut half_delta = delta / 2.0;
        let mut start_angle = 0.0_f32;
        let mut radius_double = c.height();

        if c.width() < radius_double {
            radius_double = c.width();
        }
        radius_double *= 0.8;
        let mut r = radius_double / 2.0;
        if r > self.radius {
            r = self.radius;
        }

        let cx = (c.width() - radius_double) / 2.0 + r;
        let cy = (c.height() - radius_double) / 2.0 + r;
        let label_offset = 20.0;
        let mut series_label_formatter = self.series_label_formatter.clone();
        if series_label_formatter.is_empty() {
            series_label_formatter = "{a}: {d}".to_string();
        }
        let rose_type = self.rose_type.unwrap_or_default();

        for (index, series) in self.series_list.iter().enumerate() {
            let value = values[index];
            let mut cr = value / max * (r - self.inner_radius) + self.inner_radius;
            let color = get_color(&self.series_colors, series.index.unwrap_or(index));
            // 普通饼图
            if !rose_type {
                cr = r;
                delta = value / sum * 360.0;
                half_delta = delta / 2.0;
            }
            if cr - self.inner_radius < 1.0 {
                cr = self.inner_radius + 1.0;
            }
            let mut pie = Pie {
                fill: color,
                cx,
                cy,
                r: cr,
                ir: self.inner_radius,
                start_angle,
                delta,
                ..Default::default()
            };
            if let Some(border_radius) = self.border_radius {
                pie.border_radius = border_radius;
            }

            c.pie(pie);

            let angle = start_angle + half_delta;
            let mut points = vec![];
            points.push(get_pie_point(cx, cy, cr, angle));
            let mut end = get_pie_point(cx, cy, r + label_offset, angle);
            points.push(end);

            let is_left = angle > 180.0;
            if is_left {
                end.x -= label_offset;
            } else {
                end.x += label_offset;
            }
            let mut label_margin = Box {
                left: end.x,
                top: end.y + 5.0,
                ..Default::default()
            };
            let label_option = LabelOption {
                series_name: series.name.clone(),
                value,
                percentage: value / sum,
                formatter: series_label_formatter.clone(),
                ..Default::default()
            };
            let label_text = label_option.format();

            if is_left {
                if let Ok(b) = measure_text_width_family(
                    &self.font_family,
                    self.series_label_font_size,
                    &label_text,
                ) {
                    label_margin.left -= b.width();
                }
            } else {
                label_margin.left += 3.0;
            }

            points.push(end);
            c.smooth_line(SmoothLine {
                color: Some(color),
                points,
                symbol: None,
                ..Default::default()
            });

            c.child(label_margin).text(Text {
                text: label_text,
                font_family: Some(self.font_family.clone()),
                font_size: Some(self.series_label_font_size),
                font_color: Some(self.series_label_font_color),
                ..Default::default()
            });

            start_angle += delta;
        }

        c.svg()
    }
}

#[cfg(test)]
mod tests {
    use super::PieChart;
    use pretty_assertions::assert_eq;

    #[test]
    fn pie_basic() {
        let mut pie_chart = PieChart::new(vec![
            ("rose 1", vec![40.0]).into(),
            ("rose 2", vec![38.0]).into(),
            ("rose 3", vec![32.0]).into(),
            ("rose 4", vec![30.0]).into(),
            ("rose 5", vec![28.0]).into(),
            ("rose 6", vec![26.0]).into(),
            ("rose 7", vec![22.0]).into(),
            ("rose 8", vec![18.0]).into(),
        ]);
        pie_chart.title_text = "Nightingale Chart".to_string();
        pie_chart.sub_title_text = "Fake Data".to_string();
        assert_eq!(
            include_str!("../../asset/pie_chart/basic.svg"),
            pie_chart.svg().unwrap()
        );
    }

    #[test]
    fn small_pie_basic() {
        let mut pie_chart = PieChart::new(vec![
            ("rose 1", vec![400.0]).into(),
            ("rose 2", vec![38.0]).into(),
            ("rose 3", vec![32.0]).into(),
            ("rose 4", vec![30.0]).into(),
            ("rose 5", vec![28.0]).into(),
            ("rose 6", vec![26.0]).into(),
            ("rose 7", vec![22.0]).into(),
            ("rose 8", vec![18.0]).into(),
        ]);
        pie_chart.width = 400.0;
        pie_chart.height = 300.0;
        pie_chart.title_text = "Nightingale Chart".to_string();
        pie_chart.sub_title_text = "Fake Data".to_string();
        assert_eq!(
            include_str!("../../asset/pie_chart/small_basic.svg"),
            pie_chart.svg().unwrap()
        );
    }

    #[test]
    fn not_rose_pie() {
        let mut pie_chart = PieChart::new(vec![
            ("rose 1", vec![400.0]).into(),
            ("rose 2", vec![38.0]).into(),
            ("rose 3", vec![32.0]).into(),
            ("rose 4", vec![30.0]).into(),
            ("rose 5", vec![28.0]).into(),
            ("rose 6", vec![26.0]).into(),
            ("rose 7", vec![22.0]).into(),
            ("rose 8", vec![18.0]).into(),
        ]);
        pie_chart.rose_type = Some(false);
        pie_chart.title_text = "Pie Chart".to_string();
        pie_chart.sub_title_text = "Fake Data".to_string();
        assert_eq!(
            include_str!("../../asset/pie_chart/not_rose.svg"),
            pie_chart.svg().unwrap()
        );
    }

    #[test]
    fn not_rose_radius_pie() {
        let mut pie_chart = PieChart::new(vec![
            ("rose 1", vec![400.0]).into(),
            ("rose 2", vec![38.0]).into(),
            ("rose 3", vec![32.0]).into(),
            ("rose 4", vec![30.0]).into(),
            ("rose 5", vec![28.0]).into(),
            ("rose 6", vec![26.0]).into(),
            ("rose 7", vec![22.0]).into(),
            ("rose 8", vec![18.0]).into(),
        ]);
        pie_chart.rose_type = Some(false);
        pie_chart.inner_radius = 0.0;
        pie_chart.border_radius = Some(0.0);
        pie_chart.title_text = "Pie Chart".to_string();
        pie_chart.sub_title_text = "Fake Data".to_string();
        assert_eq!(
            include_str!("../../asset/pie_chart/not_rose_radius.svg"),
            pie_chart.svg().unwrap()
        );
    }

    #[test]
    fn pie_rose_small_piece() {
        let mut pie_chart = PieChart::new(vec![
            ("rose 1", vec![40000.0]).into(),
            ("rose 2", vec![38.0]).into(),
            ("rose 3", vec![32.0]).into(),
            ("rose 4", vec![30.0]).into(),
            ("rose 5", vec![28.0]).into(),
            ("rose 6", vec![26.0]).into(),
            ("rose 7", vec![22.0]).into(),
            ("rose 8", vec![18.0]).into(),
        ]);
        pie_chart.title_text = "Nightingale Chart".to_string();
        pie_chart.sub_title_text = "Fake Data".to_string();
        assert_eq!(
            include_str!("../../asset/pie_chart/rose_small_piece.svg"),
            pie_chart.svg().unwrap()
        );
    }
}