br-addon 0.1.56

This is an addon
Documentation
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
use crate::request::{ContentType, Method, Request};
use crate::{CONFIG, GLOBAL_DATA, PLUGIN_TOOLS};
use crate::{ApiResponse, Tools};
use br_fields::Field;
use json::{object, JsonValue};
use std::any::type_name;
use crate::tables::Tables;

/// 功能接口
pub trait Action {
    /// 功能名称
    fn _name(&self) -> String {
        type_name::<Self>().rsplit("::").next().unwrap().to_lowercase()
    }
    /// 模块名称
    fn module_name(&self) -> String {
        let t = type_name::<Self>().split("::").collect::<Vec<&str>>();
        let plugin = t[2].to_lowercase();
        let module = t[3].to_lowercase();
        format!("{plugin}.{module}")
    }
    /// 插件名称
    fn addon_name(&self) -> String {
        let t = type_name::<Self>().split("::").collect::<Vec<&str>>();
        t[2].to_lowercase()
    }
    /// API 名称
    fn api(&self) -> String {
        let t = type_name::<Self>().split("::").collect::<Vec<&str>>();
        let plugin = t[2].to_lowercase();
        let module = t[3].to_lowercase();
        let action = t[4].to_lowercase();
        format!("{plugin}.{module}.{action}")
    }
    /// 是否需要密钥
    fn token(&self) -> bool {
        true
    }

    fn sort(&self) -> usize {
        99
    }
    /// 功能标题
    fn title(&self) -> &'static str;
    /// 功能描述
    fn description(&self) -> &'static str {
        ""
    }
    /// 请求地址路径
    fn path(&self) -> &'static str {
        ""
    }
    /// 请求地址参数
    fn query(&self) -> JsonValue {
        object! {}
    }
    /// 标签范围
    fn tags(&self) -> &'static [&'static str] {
        &[]
    }
    fn icon(&self) -> &'static str {
        ""
    }
    /// 是否公开
    fn public(&self) -> bool {
        true
    }
    /// 是否权限组显示
    fn auth(&self) -> bool {
        true
    }
    /// 接口类型 btn api menu
    fn interface_type(&self) -> InterfaceType {
        InterfaceType::API
    }
    /// 允许的请求类型
    fn method(&mut self) -> Method {
        Method::Post
    }
    /// 请求类型
    fn content_type(&mut self) -> ContentType {
        ContentType::Json
    }
    /// 是否检查参数
    fn params_check(&mut self) -> bool {
        true
    }
    /// 请求body参数
    fn params(&mut self) -> JsonValue {
        object! {}
    }
    /// 成功响应
    fn success(&mut self) -> ApiResponse {
        let mut data = object! {};
        data["code"] = br_fields::int::Int::new(true, "code", "编号", 10, 0).example(0.into()).swagger();
        data["message"] = br_fields::str::Str::new(true, "message", "成功消息", 256, "").example("成功".into()).swagger();
        data["data"] = br_fields::text::Json::new(true, "data", "返回数据", object! {}).swagger();
        data["success"] = br_fields::int::Switch::new(true, "success", "成功状态", true).example(true.into()).swagger();
        data["timestamp"] = br_fields::datetime::Timestamp::new(true, "timestamp", "时间戳", 0, 0.0).swagger();
        ApiResponse::success(data, "请求成功")
    }
    /// 失败响应
    fn error(&mut self) -> ApiResponse {
        let mut data = object! {};
        data["code"] = br_fields::int::Int::new(true, "code", "编号", 10, 1000).example(1000.into()).swagger();
        data["message"] = br_fields::str::Str::new(true, "message", "错误消息", 256, "").example("失败".into()).swagger();
        data["data"] = br_fields::text::Json::new(true, "data", "返回数据", object! {}).swagger();
        data["success"] = br_fields::int::Switch::new(true, "success", "成功状态", false).example(false.into()).swagger();
        data["timestamp"] = br_fields::datetime::Timestamp::new(true, "timestamp", "时间戳", 0, 0.0).swagger();
        ApiResponse::error(data, "请求失败")
    }
    /// 外部入口
    fn run(&mut self, mut request: Request) -> Result<ApiResponse, ApiResponse> {
        if self.public() && !self.method().str().is_empty() && self.method().str().to_lowercase() != request.method.str().to_lowercase() {
            return Err(ApiResponse::fail(
                -1,
                format!(
                    "Request type error: Actual [{}] Expected [{}]",
                    request.method.str(),
                    self.method().str()
                ).as_str(),
            ));
        }
        let params = self.params().clone();
        if self.params_check() {
            self.check(&mut request.query.clone(), self.query().clone())?;
            self.check(&mut request.body, params)?;
        }
        let res = self.index(request.clone());
        match res.success {
            true => Ok(res),
            false => Err(res),
        }
    }
    /// 入参验证
    fn check(&mut self, request: &mut JsonValue, params: JsonValue) -> Result<(), ApiResponse> {
        let req = request.clone();
        for (name, _) in req.entries() {
            if !params.has_key(name) {
                request.remove(name);
            }
        }
        for (name, field) in params.entries() {
            let require = field["require"].as_bool().unwrap_or(false);
            let title = field["title"].as_str().unwrap_or("");
            if request.has_key(name) {
                // 判断输入类型
                match field["mode"].as_str().unwrap() {
                    "key" => {
                        if !request[name].is_string() {
                            return Err(ApiResponse::fail(
                                900_001,
                                format!(
                                    "请求参数数据类型错误: 参数 [{}] 数据类型应为[{}]",
                                    name, field["mode"]
                                ).as_str(),
                            ));
                        }
                        if require && request[name].is_empty() {
                            return Err(ApiResponse::fail(
                                900014,
                                format!("请求参数数据类型错误: 参数 [{name}] 不能为空").as_str(),
                            ));
                        }
                    }
                    "text" | "table" | "tree" => {
                        if !request[name].is_string() {
                            return Err(ApiResponse::fail(
                                900002,
                                format!(
                                    "请求参数数据类型错误: 参数 [{}] 数据类型应为[{}]",
                                    name, field["mode"]
                                ).as_str(),
                            ));
                        }
                        if require && request[name].is_empty() {
                            return Err(ApiResponse::fail(
                                900002,
                                format!("{title} 必填").as_str(),
                            ));
                        }
                    }
                    "file" => {
                        if !request[name].is_array() && !request[name].is_string() {
                            return Err(ApiResponse::fail(
                                900003,
                                format!("参数 [{}] 数据类型应为[{}]", name, field["mode"]).as_str(),
                            ));
                        }
                        if require && request[name].is_empty() {
                            return Err(ApiResponse::fail(
                                900002,
                                format!("{title} 必填").as_str(),
                            ));
                        }
                    }
                    "int" => {
                        if require && request[name].to_string().is_empty() {
                            return Err(ApiResponse::fail(
                                900_002,
                                format!("{title} 必填").as_str(),
                            ));
                        }
                        if !request[name].to_string().is_empty() {
                            match request[name].to_string().parse::<i64>() {
                                Ok(_) => {}
                                Err(_) => {
                                    return Err(ApiResponse::fail(
                                        900013,
                                        format!(
                                            "请求参数数据类型错误: 参数 [{}] 数据类型应为[{}]",
                                            name, field["mode"]
                                        ).as_str(),
                                    ));
                                }
                            }
                        }
                    }
                    "timestamp" => {
                        if require && request[name].to_string().is_empty() {
                            return Err(ApiResponse::fail(
                                900002,
                                format!("{title} 必填").as_str(),
                            ));
                        }
                        if !request[name].to_string().is_empty() {
                            if request[name].is_array() && request[name].len() == 2 {
                                // 如果是数组,遍历每个元素
                                for item in request[name].members() {
                                    match item.to_string().parse::<f64>() {
                                        Ok(_) => {}
                                        Err(_) => {
                                            return Err(ApiResponse::fail(
                                                900_013,
                                                format!(
                                                    "请求参数数据类型错误: 参数 [{}] 数据类型应为[{}]",
                                                    name, field["mode"]
                                                ).as_str(),
                                            ));
                                        }
                                    }
                                }
                            } else {
                                match request[name].to_string().parse::<f64>() {
                                    Ok(_) => {}
                                    Err(_) => {
                                        return Err(ApiResponse::fail(
                                            900013,
                                            format!(
                                                "请求参数数据类型错误: 参数 [{}] 数据类型应为[{}]",
                                                name, field["mode"]
                                            ).as_str(),
                                        ));
                                    }
                                }
                            }
                        }
                    }
                    "float" => {
                        if require && request[name].to_string().is_empty() {
                            return Err(ApiResponse::fail(
                                900002,
                                format!("{title} 必填").as_str(),
                            ));
                        }
                        if !request[name].to_string().is_empty() {
                            match request[name].to_string().parse::<f64>() {
                                Ok(_) => {}
                                Err(_) => {
                                    return Err(ApiResponse::fail(
                                        900023,
                                        format!(
                                            "请求参数数据类型错误: 参数 [{}] 数据类型应为[{}]",
                                            name, field["mode"]
                                        ).as_str(),
                                    ));
                                }
                            }
                        }
                    }
                    "string" | "url" | "time" | "code" | "pass" | "email" | "location" | "color" | "date" | "barcode" | "datetime" | "editor" | "tel" => {
                        if !request[name].is_string() {
                            return Err(ApiResponse::fail(
                                -1,
                                format!(
                                    "请求参数数据类型错误: 参数 [{}] 数据类型应为[{}]",
                                    name, field["mode"]
                                ).as_str(),
                            ));
                        }
                        if require && request[name].is_empty() {
                            return Err(ApiResponse::fail(
                                900004,
                                format!("{title} 必填").as_str(),
                            ));
                        }
                    }
                    "dict" => {
                        if require && request[name].is_empty() {
                            return Err(ApiResponse::fail(
                                900005,
                                format!("{title} 必填").as_str(),
                            ));
                        }
                    }
                    "switch" => {
                        match request[name].to_string().parse::<bool>() {
                            Ok(e) => {
                                request[name] = e.into();
                            }
                            Err(_) => {
                                return Err(ApiResponse::fail(
                                    -1,
                                    format!("请求参数数据类型错误: 参数 [{name}] 数据类型应为[{}]", field["mode"]).as_str(),
                                ));
                            }
                        }
                    }
                    "select" => {
                        if !request[name].is_array() && !request[name].is_string() {
                            return Err(ApiResponse::fail(
                                -1,
                                format!(
                                    "请求参数数据类型错误: 参数 [{}] 数据类型应为[{}]",
                                    name, field["mode"]
                                ).as_str(),
                            ));
                        }
                        let value = if request[name].is_array() {
                            request[name].members().map(|m| m.to_string()).collect::<Vec<String>>()
                        } else {
                            request[name].to_string().split(",").map(|x| x.to_string()).collect::<Vec<String>>()
                        };
                        let option = field["option"].members().map(|m| m.as_str().unwrap_or("")).collect::<Vec<&str>>();

                        let require = field["require"].as_bool().unwrap();
                        for item in value.clone() {
                            if !option.contains(&&*item.clone()) && (item.is_empty() && require) {
                                let option = field["option"].members().map(|m| m.as_str().unwrap_or("")).collect::<Vec<&str>>().join(",");
                                return Err(ApiResponse::fail(-1, format!("请求参数选项错误: 参数 [{item}] 数据类型应为[{option}]之内").as_str()));
                            }
                        }
                        request[name] = value.into();
                    }
                    "radio" => {
                        if !request[name].is_string() {
                            return Err(ApiResponse::fail(
                                -1,
                                format!(
                                    "请求参数数据类型错误: 参数 [{}] 数据类型应为[{}] 实际为[{}]",
                                    name, field["mode"], request[name]
                                ).as_str(),
                            ));
                        }
                        let option = field["option"].members().map(|m| m.as_str().unwrap_or("")).collect::<Vec<&str>>().join(",");
                        if request[name].is_string() && !field["option"].contains(request[name].as_str().unwrap_or(""))
                        {
                            return Err(ApiResponse::fail(
                                -1,
                                format!(
                                    "请求参数选项错误: 参数 [{}] 数据 [{}] 应为 [{}] 之一",
                                    name, request[name], option
                                ).as_str(),
                            ));
                        }
                    }
                    "array" | "polygon" => {
                        if !request[name].is_array() {
                            return Err(ApiResponse::fail(
                                900_009,
                                format!(
                                    "请求参数数据类型错误: 参数 [{}] 数据类型应为[{}]",
                                    name, field["mode"]
                                ).as_str(),
                            ));
                        }
                        if require && request[name].is_empty() {
                            return Err(ApiResponse::fail(
                                900010,
                                format!("请求参数数据类型错误: 参数 [{name}] 不能为空").as_str(),
                            ));
                        }
                    }
                    "object" => {
                        if !request[name].is_object() {
                            return Err(ApiResponse::fail(
                                900009,
                                format!(
                                    "请求参数数据类型错误: 参数 [{}] 数据类型应为[{}]",
                                    name, field["mode"]
                                ).as_str(),
                            ));
                        }
                        if require && request[name].is_empty() {
                            return Err(ApiResponse::fail(
                                900006,
                                format!("{title} 必填").as_str(),
                            ));
                        }
                    }
                    _ => {
                        println!("检查未知类型: {}", field["mode"])
                    }
                }
            } else {
                if require {
                    return Err(ApiResponse::fail(
                        900007,
                        format!("{title} 必填").as_str(),
                    ));
                }
                request[name] = field["def"].clone();
            }
        }
        Ok(())
    }
    /// 内部入口
    fn index(&mut self, request: Request) -> ApiResponse;
    #[cfg(any(feature = "sqlite", feature = "mssql", feature = "mysql", feature = "pgsql"))]
    fn table_select(
        &mut self,
        request: JsonValue,
        table_name: &str,
        fields: Vec<&str>,
    ) -> JsonValue {
        self.table().main_select_fields(table_name, fields).params(request.clone()).get_table_select()
    }


    /// 列表表格渲染
    /// * table_name 表名
    /// * fields 全部模型字段集合
    /// * hidd_field 需要隐藏的字段集合
    /// * show_field 需要显示的字段集合
    /// * search_fields 搜索字段集合
    /// * filter_fields 高级搜索字段集合
    #[allow(clippy::too_many_arguments)]
    #[cfg(any(feature = "sqlite", feature = "mssql", feature = "mysql", feature = "pgsql"))]
    fn table_list(
        &mut self,
        request: JsonValue,
        table_name: &str,
        fields: JsonValue,
        hidd_field: Vec<&str>,
        show_field: Vec<&str>,
        search_fields: Vec<&str>,
        filter_fields: Vec<&str>,
    ) -> JsonValue {
        self.table().main_table_fields(table_name, fields, hidd_field, show_field).search_fields(search_fields).filter_fields(filter_fields).params(request).get_table()
    }
    #[allow(clippy::too_many_arguments)]
    #[cfg(any(feature = "sqlite", feature = "mssql", feature = "mysql", feature = "pgsql"))]
    fn table(&mut self) -> Tables {
        Tables::new(self.tools().db.clone())
    }

    /// 使用工具
    fn tools(&mut self) -> Tools {
        let tools = PLUGIN_TOOLS.lock().unwrap();
        let tools = tools.get("tools").unwrap().clone();
        tools
    }
    /// 使用配置
    fn config(&mut self, name: &str) -> JsonValue {
        if CONFIG.lock().unwrap().get(name).is_none() {
            object! {}
        } else {
            CONFIG.lock().unwrap().get(name).unwrap().clone()
        }
    }
    /// 按钮信息
    /// * cnd 显示条件 vec![vec!["xxx","=","yyy"],vec!["zzz","=","eee"]]
    fn btn(&mut self) -> Btn {
        let mut btn = Btn::new(self.api().as_str());
        btn.fields(self.params().clone());
        btn.tags(self.tags());
        btn.icon(self.icon());
        btn.desc(self.description());
        btn.auth(self.auth());
        btn.public(self.public());
        btn.title(self.title());
        btn.btn_type(BtnType::Api);
        btn.btn_color(BtnColor::Primary);
        btn.path(self.api().clone().replace(".", "/").as_str());
        btn.pass(false);
        btn.addon();
        btn
    }
    /// 设置全局变量
    fn set_global_data(&mut self, key: &str, value: JsonValue) {
        GLOBAL_DATA.with(|data| {
            data.borrow_mut()[key] = value;
        });
    }
    /// 获取全局变量数据
    fn get_global_data(&mut self) -> JsonValue {
        GLOBAL_DATA.with(|data| {
            data.borrow().clone()
        })
    }
    /// 获取全局变量指定字段数据
    fn get_global_data_key(&mut self, key: &str) -> JsonValue {
        GLOBAL_DATA.with(|data| {
            data.borrow()[key].clone()
        })
    }
}
#[derive(Debug, Clone)]
pub struct Btn {
    api: String,
    title: String,
    desc: String,
    tags: &'static [&'static str],
    auth: bool,
    public: bool,
    btn_type: BtnType,
    color: BtnColor,
    icon: String,
    cnd: Vec<JsonValue>,
    url: String,
    path: String,
    fields: JsonValue,
    addon: String,
    version: usize,
    /// 是否需要密码
    pass: bool,
}
impl Btn {
    pub fn new(api: &str) -> Self {
        Self {
            api: api.to_string(),
            title: "".to_string(),
            desc: "".to_string(),
            btn_type: BtnType::Api,
            color: BtnColor::Primary,
            icon: "".to_string(),
            auth: false,
            public: false,
            cnd: vec![],
            url: "".to_string(),
            path: "".to_string(),
            fields: object! {},
            tags: &[],
            pass: false,
            addon: "".to_string(),
            version: 0,
        }
    }

    pub fn addon(&mut self) -> &mut Self {
        self.addon = self.api.split('.').nth(0).unwrap().to_string();
        self
    }
    pub fn path(&mut self, path: &str) -> &mut Self {
        self.path = path.to_string();
        self
    }
    pub fn cnd(&mut self, cnd: Vec<JsonValue>) -> &mut Self {
        self.cnd = cnd;
        self
    }
    pub fn version(&mut self, version: usize) -> &mut Self {
        self.version = version;
        self
    }
    pub fn btn_type(&mut self, btn_type: BtnType) -> &mut Self {
        self.btn_type = btn_type;
        self
    }
    pub fn btn_color(&mut self, btn_color: BtnColor) -> &mut Self {
        self.color = btn_color;
        self
    }
    pub fn fields(&mut self, fields: JsonValue) -> &mut Self {
        self.fields = fields;
        self
    }
    pub fn pass(&mut self, pass: bool) -> &mut Self {
        self.pass = pass;
        self
    }
    pub fn url(&mut self, url: &str) -> &mut Self {
        self.url = url.to_string();
        self
    }
    pub fn title(&mut self, title: &str) -> &mut Self {
        self.title = title.to_string();
        self
    }
    pub fn desc(&mut self, desc: &str) -> &mut Self {
        self.desc = desc.to_string();
        self
    }
    pub fn tags(&mut self, tags: &'static [&'static str]) -> &mut Self {
        self.tags = tags;
        self
    }
    pub fn public(&mut self, public: bool) -> &mut Self {
        self.public = public;
        self
    }
    pub fn auth(&mut self, auth: bool) -> &mut Self {
        self.auth = auth;
        self
    }
    pub fn icon(&mut self, icon: &str) -> &mut Self {
        self.icon = icon.to_string();
        self
    }
    pub fn json(&mut self) -> JsonValue {
        let color = match self.version {
            0 => self.color.clone().str(),
            _ => self.color.clone().str_v_1()
        };
        object! {
            addon:self.addon.to_string() ,
            api:self.api.clone(),
            title:self.title.clone(),
            desc:self.desc.clone(),
            auth:self.auth,
            public:self.public,
            btn_type:self.btn_type.clone().str(),
            color:color,
            icon:self.icon.clone(),
            cnd:self.cnd.clone(),
            url:self.url.clone(),
            path:self.path.clone(),
            fields:self.fields.clone(),
            tags:self.tags,
            pass:self.pass,
        }
    }
}

/// 接口类型
#[derive(Debug, Clone)]
pub enum InterfaceType {
    API,
    BTN,
    MENU,
    OPENAPI,
}

impl InterfaceType {
    pub fn str(&self) -> &'static str {
        match self {
            InterfaceType::API => "api",
            InterfaceType::BTN => "btn",
            InterfaceType::MENU => "menu",
            InterfaceType::OPENAPI => "openapi",
        }
    }
    pub fn types() -> Vec<&'static str> {
        vec!["api", "btn", "menu", "openapi"]
    }
}

/// 按钮类型
#[derive(Debug, Clone)]
pub enum BtnType {
    /// 表单
    Form,
    /// 表单下载
    FormDownload,
    /// 表单自定义
    FormCustom,
    FormData,
    /// 外部跳转
    Url,
    /// api请求
    Api,
    /// 下载
    Download,
    /// 内部跳转
    Path,
    /// 弹窗-定制页面
    DialogCustom,
    /// 表单->API->弹出自定义窗口
    FormApiDialogCustom,
    /// 预览
    Preview,
}

impl BtnType {
    fn str(self) -> &'static str {
        match self {
            BtnType::Form => "form",
            BtnType::FormDownload => "form_download",
            BtnType::FormCustom => "form_custom",
            BtnType::FormData => "form_data",
            BtnType::Api => "api",
            BtnType::Download => "download",
            BtnType::Url => "url",
            BtnType::Path => "path",
            BtnType::DialogCustom => "dialog_custom",
            BtnType::FormApiDialogCustom => "form_api_dialog_custom",
            BtnType::Preview => "preview",
        }
    }
}
/// 按钮颜色
#[derive(Debug, Clone)]
pub enum BtnColor {
    Primary,
    Red,
    Yellow,
    Green,
}

impl BtnColor {
    fn str(self) -> &'static str {
        match self {
            BtnColor::Primary => "primary",
            BtnColor::Red => "negative",
            BtnColor::Yellow => "warning",
            BtnColor::Green => "positive",
        }
    }
    fn str_v_1(self) -> &'static str {
        match self {
            BtnColor::Primary => "normal",
            BtnColor::Red => "danger",
            BtnColor::Yellow => "warning",
            BtnColor::Green => "success",
        }
    }
}


pub struct Dashboard {
    /// 名称
    title: String,
    /// 数据
    data: JsonValue,
    /// 显示样式
    model: DashboardModel,
    /// 渲染样式
    class: String,
    /// 图标
    icon: String,
    /// 描述
    desc: String,
    ///数据请求接口
    api: String,
    ///用户选项,同时也是api接收的参数
    options: JsonValue,
}
impl Dashboard {
    pub fn new(title: &str) -> Dashboard {
        Dashboard {
            title: title.to_string(),
            data: JsonValue::Null,
            model: DashboardModel::Number,
            class: "col-4".to_string(),
            icon: "".to_string(),
            desc: "".to_string(),
            api: "".to_string(),
            options: JsonValue::Null,
        }
    }
    pub fn options(&mut self, options: JsonValue) -> &mut Self {
        self.options = options;
        self
    }
    pub fn api(&mut self, api: &str) -> &mut Self {
        self.api = api.to_string();
        self
    }
    pub fn data(&mut self, data: JsonValue) -> &mut Self {
        self.data = data;
        self
    }
    pub fn class(&mut self, name: &str) -> &mut Self {
        self.class = name.to_string();
        self
    }
    pub fn icon(&mut self, name: &str) -> &mut Self {
        self.icon = name.to_string();
        self
    }
    pub fn model(&mut self, dashboard_model: DashboardModel) -> &mut Self {
        self.model = dashboard_model;
        self
    }
    pub fn desc(&mut self, desc: &str) -> &mut Self {
        self.desc = desc.to_string();
        self
    }
    pub fn json(&self) -> JsonValue {
        object! {
            title: self.title.clone(),
            data: self.data.clone(),
            class: self.class.clone(),
            icon: self.icon.clone(),
            model: self.model.str(),
            desc: self.desc.clone(),
            api: self.api.clone(),
            options:self.options.clone(),
        }
    }
}

pub enum DashboardModel {
    /// 数字
    Number,
    /// 柱状图
    EchartsBar,
    /// 堆叠柱状图
    EchartsStackedBar,
    /// 动态排序的柱状图
    EchartsBarRace,
    /// 饼图
    EchartsPie,
    /// 中空饼图
    EchartsDoughnut,
    /// 堆叠折线图
    EchartsStackedLine,
    /// 面积填充的堆叠折线图
    EchartsStackedLineArea,
    /// 地图
    EchartsGeoGraph,
}

impl DashboardModel {
    pub fn str(&self) -> &'static str {
        match self {
            Self::Number => "number",
            Self::EchartsBar => "echarts-bar",
            Self::EchartsStackedBar => "echarts-stacked_bar",
            Self::EchartsBarRace => "echarts-bar_race",
            Self::EchartsPie => "echarts-pie",
            Self::EchartsDoughnut => "echarts-doughnut",
            Self::EchartsStackedLine => "echarts-stacked_line",
            Self::EchartsStackedLineArea => "echarts-stacked_line_area",
            Self::EchartsGeoGraph => "echarts-geo_graph",
        }
    }
}