Skip to main content

br_addon/
tables.rs

1use br_db::Db;
2use br_fields::Field;
3use json::{array, object, JsonValue};
4use std::collections::HashMap;
5
6#[allow(clippy::too_many_arguments)]
7#[cfg(any(
8    feature = "sqlite",
9    feature = "mssql",
10    feature = "mysql",
11    feature = "pgsql"
12))]
13pub struct Tables {
14    /// 主数据表名称
15    main_table: String,
16    /// 数据库
17    db: Db,
18    /// 记录总数量
19    total: i64,
20    /// 字段数据
21    fields: Vec<JsonValue>,
22    /// 连表查询
23    join_params: Vec<Vec<String>>,
24    /// 字段值集合
25    fields_keys: Vec<String>,
26    /// 联表字段
27    join_fields: Vec<String>,
28    /// 隐藏字段
29    hide_fields: Vec<String>,
30    /// 显示字段
31    show_fields: Vec<String>,
32    /// 合计字段
33    total_fields: Vec<String>,
34    /// 数据
35    data: JsonValue,
36    /// 页数
37    page: usize,
38    /// 总页数
39    pages: i64,
40    /// 每页数量
41    limit: usize,
42    /// 搜索内容
43    search: String,
44    /// 搜索字段
45    search_fields: Vec<String>,
46    /// 搜索框名称
47    search_name: String,
48    /// 可以编辑字段
49    edit_fields: Vec<String>,
50    /// 排序
51    /// array![array!["id",false]]
52    order: JsonValue,
53    /// 过滤条件
54    /// array![array!["id","=","*"]]
55    where_and: JsonValue,
56    /// 过滤条件
57    /// array![array!["id","=","*"]]
58    where_or: JsonValue,
59    /// 过滤字段
60    filter_fields: Vec<String>,
61    /// 表单关联字段
62    table_fields: Vec<String>,
63    /// 表单关联多选字段
64    table_multiple_fields: Vec<String>,
65    /// 树形关联字段
66    tree_fields: Vec<String>,
67    /// JSON字段
68    json_fields: Vec<String>,
69    /// 地图字段
70    location_fields: Vec<String>,
71    /// 显示的主键
72    primary_key: String,
73    /// 选中值
74    value: Vec<String>,
75    /// 树形pid
76    pid_id: String,
77    /// 字段索引缓存(field name → field metadata)
78    all_fields_map: JsonValue,
79}
80impl Tables {
81    pub fn params_table(mut params: JsonValue) -> JsonValue {
82        params["page"] = br_fields::int::Int::new(false, "page", "页数", 10, 1)
83            .example(1.into())
84            .field();
85        params["limit"] = br_fields::int::Int::new(false, "limit", "行数", 10, 10)
86            .example(10.into())
87            .field();
88        params["order"] = br_fields::text::Array::new(false, "order", "排序", array![]).field();
89        params["search"] = br_fields::str::Str::new(false, "search", "搜索", 200, "")
90            .example("".into())
91            .field();
92        params["where_or"] = br_fields::text::Array::new(false, "where_or", "查询条件", array![])
93            .example(array![])
94            .field();
95        params["where_and"] = br_fields::text::Array::new(false, "where_and", "查询条件", array![])
96            .example(array![])
97            .field();
98        params["params"] =
99            br_fields::text::Object::new(false, "params", "关联数据参数", object! {})
100                .describe("如果是表单就是表单里的其他字段")
101                .example(object! {})
102                .field();
103        params
104    }
105    pub fn params_table_tree(mut params: JsonValue) -> JsonValue {
106        params["pid"] = br_fields::str::Str::new(false, "pid", "上级ID", 50, "")
107            .example("".into())
108            .field();
109        Tables::params_table_select(params)
110    }
111    pub fn params_table_select(mut params: JsonValue) -> JsonValue {
112        params["value"] = br_fields::text::Array::new(false, "value", "已选中值", array![]).field();
113        params["primary_key"] =
114            br_fields::str::Str::new(false, "primary_key", "显示内容的字段", 50, "id").field();
115        Tables::params_table(params)
116    }
117    pub fn params_table_select_tree(mut params: JsonValue) -> JsonValue {
118        params["pid"] = br_fields::str::Str::new(false, "pid", "上级ID", 20, "")
119            .example("".into())
120            .field();
121        params["value"] = br_fields::text::Array::new(false, "value", "已选中值", array![]).field();
122        Tables::params_table(params)
123    }
124    pub fn new(db: Db) -> Self {
125        Self {
126            main_table: "".to_string(),
127            db,
128            total: 0,
129            fields: vec![],
130            join_params: vec![],
131            fields_keys: vec![],
132            data: array![],
133            page: 1,
134            pages: 0,
135            limit: 10,
136            search: "".to_string(),
137            search_fields: vec![],
138            search_name: "".to_string(),
139            edit_fields: vec![],
140            order: array![],
141            where_and: array![],
142            where_or: array![],
143            filter_fields: vec![],
144            table_fields: vec![],
145            table_multiple_fields: vec![],
146            tree_fields: vec![],
147            json_fields: vec![],
148            location_fields: vec![],
149            primary_key: "".to_string(),
150            value: vec![],
151            join_fields: vec![],
152            hide_fields: vec![],
153            show_fields: vec![],
154            total_fields: vec![],
155            pid_id: "".to_string(),
156            all_fields_map: object! {},
157        }
158    }
159    pub fn main_table_fields(
160        &mut self,
161        table: &str,
162        fields: JsonValue,
163        hide_fields: Vec<&str>,
164        show_fields: Vec<&str>,
165    ) -> &mut Self {
166        self.main_table = table.to_string();
167        self.hide_fields = hide_fields.iter().map(|s| s.to_string()).collect();
168        self.show_fields = show_fields.iter().map(|s| s.to_string()).collect();
169        self.fields = fields
170            .entries()
171            .map(|(_, x)| x.clone())
172            .collect::<Vec<JsonValue>>();
173        self
174    }
175    pub fn join_fields(&mut self, table: &str, mut fields: JsonValue, index: isize) -> &mut Self {
176        for (field, item) in fields.entries_mut() {
177            if self.main_table != table {
178                item["field"] = format!("{table}_{field}").into();
179                item["field_table"] = table.into();
180                item["field_table_field"] = field.into();
181            }
182
183            match index {
184                x if x > -1 => {
185                    // 插入
186                    self.fields.insert(x as usize, item.clone());
187                }
188                _ => {
189                    // 尾部添加
190                    self.fields.push(item.clone());
191                }
192            }
193            self.join_fields.push(format!("{table}.{field}"));
194        }
195        self
196    }
197    pub fn fields(&mut self, fields: JsonValue) -> &mut Self {
198        self.fields = fields
199            .entries()
200            .map(|(_, x)| x.clone())
201            .collect::<Vec<JsonValue>>();
202        self
203    }
204    pub fn hide_fields(&mut self, hide_fields: Vec<&str>) -> &mut Self {
205        self.hide_fields = hide_fields.iter().map(|s| s.to_string()).collect();
206        self
207    }
208    pub fn show_fields(&mut self, show_fields: Vec<&str>) -> &mut Self {
209        self.show_fields = show_fields.iter().map(|s| s.to_string()).collect();
210        self
211    }
212    pub fn total_fields(&mut self, fields: Vec<&str>) -> &mut Self {
213        self.total_fields = fields.iter().map(|s| s.to_string()).collect();
214        self
215    }
216    fn set_fields(&mut self, field: &str, mode: &str) {
217        match mode {
218            "table" => self.table_fields.push(field.to_string()),
219            "table_multiple" => {
220                self.table_multiple_fields.push(field.to_string());
221                self.json_fields.push(field.to_string());
222            }
223            "tree" => self.tree_fields.push(field.to_string()),
224            "object" | "array" | "polygon" => self.json_fields.push(field.to_string()),
225            "location" => self.location_fields.push(field.to_string()),
226            _ => {}
227        }
228    }
229    pub fn join_table(
230        &mut self,
231        main_table: &str,
232        main_field: &str,
233        join_table: &str,
234        join_field: &str,
235    ) -> &mut Self {
236        self.join_params.push(vec![
237            main_table.to_string(),
238            main_field.to_string(),
239            join_table.to_string(),
240            join_field.to_string(),
241        ]);
242        self
243    }
244    pub fn main_select_fields(&mut self, table: &str, mut show_fields: Vec<&str>) -> &mut Self {
245        self.main_table = table.to_string();
246        show_fields.insert(0, "id");
247        self.fields_keys = show_fields.into_iter().map(|x| x.to_string()).collect();
248        self.search_fields = self.fields_keys.clone();
249        self
250    }
251
252    pub fn edit_fields(&mut self, fields: Vec<&str>) -> &mut Self {
253        self.edit_fields = fields.iter().map(|s| s.to_string()).collect();
254        self
255    }
256    pub fn search_fields(&mut self, fields: Vec<&str>) -> &mut Self {
257        let mut search_name = vec![];
258        let all_fields = self
259            .fields
260            .iter()
261            .map(|x| (x["field"].to_string(), x.clone()))
262            .collect::<HashMap<String, JsonValue>>();
263        for key in fields.clone() {
264            if let Some(field_info) = all_fields.get(key) {
265                self.search_fields.push(key.to_string());
266                search_name.push(field_info["title"].to_string());
267            }
268        }
269        self.search_name = search_name.join("/");
270        self
271    }
272    /// 条件过滤
273    pub fn filter_fields(&mut self, fields: Vec<&str>) -> &mut Self {
274        let all_fields = self
275            .fields
276            .iter()
277            .map(|x| (x["field"].to_string(), x.clone()))
278            .collect::<HashMap<String, JsonValue>>();
279        for key in fields.clone() {
280            if all_fields.contains_key(key) {
281                self.filter_fields.push(key.to_string());
282            } else {
283                log::warn!(
284                    "filter_fields: unknown field '{}' in table '{}'",
285                    key,
286                    self.main_table
287                );
288            }
289        }
290        self
291    }
292    /// 请求参数
293    pub fn params(&mut self, request: JsonValue) -> &mut Self {
294        if request.has_key("page") {
295            self.page = request["page"].as_usize().unwrap_or(1);
296        }
297        if request.has_key("limit") {
298            self.limit = request["limit"].as_usize().unwrap_or(10);
299        }
300        if request.has_key("where_and") {
301            self.where_and = request["where_and"].clone();
302        }
303        if request.has_key("where_or") {
304            self.where_or = request["where_or"].clone();
305        }
306
307        if request.has_key("pid") {
308            self.pid_id = if let Some(s) = request["pid"].as_str() {
309                s.to_string()
310            } else if request["pid"].is_number() {
311                request["pid"].to_string()
312            } else {
313                String::new()
314            };
315        }
316
317        if request.has_key("order") {
318            for item in request["order"].members() {
319                let _ = self.order.push(item.clone());
320            }
321        }
322        if request.has_key("search") {
323            self.search = request["search"].as_str().unwrap_or("").to_string();
324        }
325        if request.has_key("primary_key") {
326            self.primary_key = request["primary_key"].as_str().unwrap_or("").to_string();
327        }
328        if request.has_key("value") {
329            self.value = request["value"]
330                .members()
331                .map(|x| x.as_str().unwrap_or("").to_string())
332                .filter(|x| !x.is_empty())
333                .collect();
334        }
335        self
336    }
337
338    fn db_search(&mut self) {
339        if !self.search.is_empty() {
340            let mut t = vec![];
341            for value in self.search_fields.clone() {
342                let field = self.all_fields_map[value.as_str()].clone();
343                if field.has_key("field_table") {
344                    t.push(format!(
345                        "{}.{}",
346                        field["field_table"].clone(),
347                        field["field_table_field"].clone()
348                    ));
349                } else {
350                    t.push(value);
351                }
352            }
353            self.db
354                .where_and(&t.join("|"), "like", format!("%{}%", self.search).into());
355        }
356    }
357    fn db_where(&mut self) {
358        for value in self.where_or.members() {
359            let field = self.all_fields_map[value[0].to_string()].clone();
360            if field.has_key("field_table") {
361                self.db.where_or(
362                    format!(
363                        "{}.{}",
364                        field["field_table"].clone(),
365                        field["field_table_field"].clone()
366                    )
367                    .as_str(),
368                    value[1].as_str().unwrap_or("="),
369                    value[2].clone(),
370                );
371            } else {
372                self.db.where_or(
373                    value[0].as_str().unwrap_or_default(),
374                    value[1].as_str().unwrap_or("="),
375                    value[2].clone(),
376                );
377            }
378        }
379        for value in self.where_and.members() {
380            let field_name = value[0].as_str().unwrap_or_default();
381            let field = self.all_fields_map[field_name].clone();
382
383            // table_multiple 字段是 JSON 数组 TEXT 列,用 LIKE + where_or 匹配
384            if self.table_multiple_fields.contains(&field_name.to_string()) {
385                let filter_ids: Vec<String> = if value[2].is_array() {
386                    value[2]
387                        .members()
388                        .filter_map(|v| {
389                            let s = v.as_str().unwrap_or("");
390                            if s.is_empty() {
391                                None
392                            } else {
393                                Some(s.to_string())
394                            }
395                        })
396                        .collect()
397                } else {
398                    let s = value[2].as_str().unwrap_or("");
399                    s.split(',')
400                        .map(|x| x.trim().to_string())
401                        .filter(|x| !x.is_empty())
402                        .collect()
403                };
404                if filter_ids.is_empty() {
405                    continue;
406                }
407                for id in &filter_ids {
408                    self.db
409                        .where_or(field_name, "like", format!("%{}%", id).into());
410                }
411                continue;
412            }
413
414            if field.has_key("field_table") {
415                self.db.where_and(
416                    format!(
417                        "{}.{}",
418                        field["field_table"].clone(),
419                        field["field_table_field"].clone()
420                    )
421                    .as_str(),
422                    value[1].as_str().unwrap_or("="),
423                    value[2].clone(),
424                );
425            } else {
426                self.db.where_and(
427                    value[0].as_str().unwrap_or_default(),
428                    value[1].as_str().unwrap_or("="),
429                    value[2].clone(),
430                );
431            }
432        }
433    }
434    fn db_order(&mut self) {
435        for item in self.order.members() {
436            let field = self.all_fields_map[item[0].to_string()].clone();
437            if field.has_key("field_table") {
438                self.db.order(
439                    format!(
440                        "{}.{}",
441                        field["field_table"].clone(),
442                        field["field_table_field"].clone()
443                    )
444                    .as_str(),
445                    item[1].as_bool().unwrap_or(false),
446                );
447            } else {
448                self.db.order(
449                    format!("{}.{}", self.main_table, item[0]).as_str(),
450                    item[1].as_bool().unwrap_or(false),
451                );
452            }
453        }
454    }
455    fn db_fields(&mut self) {
456        let mut all_fields = object! {};
457        let _ = self
458            .fields
459            .iter()
460            .map(|x| all_fields.insert(x["field"].as_str().unwrap_or_default(), x.clone()))
461            .collect::<Vec<_>>();
462
463        if !self.hide_fields.is_empty() {
464            for field in self.hide_fields.clone() {
465                if all_fields.has_key(&field) {
466                    all_fields.remove(&field);
467                    continue;
468                }
469            }
470        }
471
472        if !self.show_fields.is_empty() {
473            self.show_fields.insert(0, "id".to_string());
474            let mut f = object! {};
475            for field in self.show_fields.clone() {
476                if all_fields.has_key(&field) {
477                    let _ = f.insert(&field.clone(), all_fields[field].clone());
478                }
479            }
480            all_fields = f;
481        }
482
483        for (field, item) in all_fields.entries() {
484            let mode = item["mode"].to_string();
485            self.set_fields(field, mode.as_str());
486        }
487
488        self.fields = all_fields
489            .entries()
490            .map(|(_, x)| x.clone())
491            .collect::<Vec<JsonValue>>();
492
493        self.all_fields_map = all_fields;
494
495        if !self.fields_keys.is_empty() {
496            self.db.field(self.fields_keys.join(",").as_str());
497        }
498        if !self.json_fields.is_empty() {
499            self.db.json(self.json_fields.join(",").as_str());
500        }
501        if !self.location_fields.is_empty() {
502            self.db.location(self.location_fields.join(",").as_str());
503        }
504    }
505    fn db_join(&mut self) {
506        if !self.join_fields.is_empty() {
507            self.db
508                .join_fields(self.join_fields.iter().map(|x| x.as_str()).collect());
509        }
510        for item in self.join_params.iter() {
511            self.db.join(&item[0], &item[1], &item[2], &item[3]);
512        }
513    }
514    fn db_total(&mut self) {
515        self.total = self.db.clone().count().as_i64().unwrap_or(0);
516        self.pages = if self.limit > 0 {
517            (self.total + self.limit as i64 - 1) / self.limit as i64
518        } else {
519            0
520        };
521    }
522    fn resolve_table_field_batch(&mut self, field: &str) -> JsonValue {
523        let field_info = self.all_fields_map[field].clone();
524        let mut info = field_info.clone();
525        let _ = info["fields"].push("id");
526        let fields_k = info["fields"]
527            .members()
528            .map(|x| x.as_str().unwrap_or_default())
529            .collect::<Vec<&str>>();
530        let table_name = info["table"].as_str().unwrap_or_default().to_string();
531        let field_str = fields_k.join(",");
532
533        let mut ids: Vec<String> = vec![];
534        for item in self.data.members() {
535            let key = item[field].as_str().unwrap_or("");
536            if !key.is_empty() && !ids.contains(&key.to_string()) {
537                ids.push(key.to_string());
538            }
539        }
540
541        let mut lookup = object! {};
542        if ids.is_empty() {
543            return lookup;
544        }
545
546        let rows = self
547            .db
548            .table(&table_name)
549            .where_and("id", "in", ids.into())
550            .field(&field_str)
551            .select();
552        for mut row in rows.members().cloned() {
553            let id = row["id"].to_string();
554            row.remove("id");
555            let label = row
556                .entries()
557                .map(|(_, v)| v.to_string())
558                .collect::<Vec<String>>();
559            lookup[id.as_str()] = object! {
560                value: id.clone(),
561                label: label.join(" | ").clone(),
562            };
563        }
564        lookup
565    }
566
567    fn resolve_table_multiple_field_batch(&mut self, field: &str) -> JsonValue {
568        let field_info = self.all_fields_map[field].clone();
569        let mut info = field_info.clone();
570        let _ = info["fields"].push("id");
571        let fields_k = info["fields"]
572            .members()
573            .map(|x| x.as_str().unwrap_or_default())
574            .collect::<Vec<&str>>();
575        let table_name = info["table"].as_str().unwrap_or_default().to_string();
576        let field_str = fields_k.join(",");
577
578        let mut ids: Vec<String> = vec![];
579        for item in self.data.members() {
580            let arr = &item[field];
581            if arr.is_array() {
582                for id_val in arr.members() {
583                    let key = id_val.as_str().unwrap_or("");
584                    if !key.is_empty() && !ids.contains(&key.to_string()) {
585                        ids.push(key.to_string());
586                    }
587                }
588            }
589        }
590
591        let mut lookup = object! {};
592        if ids.is_empty() {
593            return lookup;
594        }
595
596        let rows = self
597            .db
598            .table(&table_name)
599            .where_and("id", "in", ids.into())
600            .field(&field_str)
601            .select();
602        for mut row in rows.members().cloned() {
603            let id = row["id"].to_string();
604            row.remove("id");
605            let label = row
606                .entries()
607                .map(|(_, v)| v.to_string())
608                .collect::<Vec<String>>();
609            lookup[id.as_str()] = object! {
610                value: id.clone(),
611                label: label.join(" | ").clone(),
612            };
613        }
614        lookup
615    }
616
617    fn resolve_tree_field(&mut self, field: &str, table_data: &mut JsonValue, key: &str) {
618        if table_data[field].has_key(key) {
619            return;
620        }
621        let field_info = self.all_fields_map[field].clone();
622        let mut info = field_info.clone();
623        let pid_field = info["pid_field"].clone().to_string();
624        let _ = info["fields"].push("id");
625        let _ = info["fields"].push(pid_field.clone());
626        let fields_k = info["fields"]
627            .members()
628            .map(|x| x.as_str().unwrap_or_default())
629            .collect::<Vec<&str>>();
630        let table_name = info["table"].as_str().unwrap_or_default().to_string();
631        let field_str = fields_k.join(",");
632
633        let mut find = self
634            .db
635            .table(&table_name)
636            .where_and("id", "=", key.into())
637            .field(&field_str)
638            .find();
639        let mut pid = find[pid_field.clone()].to_string();
640        let mut name_list = vec![];
641        let id = find["id"].to_string();
642        find.remove("id");
643        find.remove(&pid_field);
644        let label = find
645            .entries()
646            .map(|(_, v)| v.to_string())
647            .collect::<Vec<String>>();
648        name_list.push(label.join(" | ").clone());
649        loop {
650            if pid.is_empty() {
651                break;
652            }
653            let mut t = self
654                .db
655                .table(&table_name)
656                .where_and("id", "=", pid.clone().into())
657                .field(&field_str)
658                .find();
659            pid = t[pid_field.clone()].to_string();
660            t.remove("id");
661            t.remove(&pid_field);
662            let label = t
663                .entries()
664                .map(|(_, v)| v.to_string())
665                .collect::<Vec<String>>();
666            name_list.push(label.join(" | ").clone());
667        }
668        name_list.reverse();
669        if !table_data.has_key(field) {
670            table_data[field] = object! {};
671        }
672        table_data[field][key] = object! {
673            value: id.clone(),
674            label: name_list.join("/").clone(),
675        };
676    }
677
678    fn db_table(&mut self) {
679        let mut table_lookups: HashMap<String, JsonValue> = HashMap::new();
680        for field in self.table_fields.clone() {
681            table_lookups.insert(field.clone(), self.resolve_table_field_batch(&field));
682        }
683
684        let mut multiple_lookups: HashMap<String, JsonValue> = HashMap::new();
685        for field in self.table_multiple_fields.clone() {
686            multiple_lookups.insert(
687                field.clone(),
688                self.resolve_table_multiple_field_batch(&field),
689            );
690        }
691
692        let mut tree_data = object! {};
693        let tree_fields = self.tree_fields.clone();
694        let mut tree_keys: Vec<(String, String)> = vec![];
695        for item in self.data.members() {
696            for field in tree_fields.iter() {
697                let key = item[field].as_str().unwrap_or("");
698                if !key.is_empty() {
699                    tree_keys.push((field.clone(), key.to_string()));
700                }
701            }
702        }
703        for (field, key) in tree_keys {
704            self.resolve_tree_field(&field, &mut tree_data, &key);
705        }
706
707        for item in self.data.members_mut() {
708            for field in self.table_fields.iter() {
709                let key = item[field].as_str().unwrap_or("");
710                if key.is_empty() {
711                    continue;
712                }
713                if let Some(lookup) = table_lookups.get(field.as_str()) {
714                    if lookup.has_key(key) {
715                        item[field] = lookup[key].clone();
716                    }
717                }
718            }
719            for field in tree_fields.iter() {
720                let key = item[field].as_str().unwrap_or("");
721                if key.is_empty() {
722                    continue;
723                }
724                if tree_data.has_key(field) && tree_data[field].has_key(key) {
725                    item[field] = tree_data[field][key].clone();
726                }
727            }
728            for field in self.table_multiple_fields.iter() {
729                let ids = item[field].clone();
730                if !ids.is_array() || ids.is_empty() {
731                    item[field] = array![];
732                    continue;
733                }
734                let mut result = array![];
735                if let Some(lookup) = multiple_lookups.get(field.as_str()) {
736                    for id_val in ids.members() {
737                        let key = id_val.as_str().unwrap_or("");
738                        if !key.is_empty() && lookup.has_key(key) {
739                            let _ = result.push(lookup[key].clone());
740                        }
741                    }
742                }
743                item[field] = result;
744            }
745        }
746    }
747    fn db_table_tree(&mut self, pid_field: &str) {
748        let mut table_lookups: HashMap<String, JsonValue> = HashMap::new();
749        for field in self.table_fields.clone() {
750            table_lookups.insert(field.clone(), self.resolve_table_field_batch(&field));
751        }
752
753        let mut multiple_lookups: HashMap<String, JsonValue> = HashMap::new();
754        for field in self.table_multiple_fields.clone() {
755            multiple_lookups.insert(
756                field.clone(),
757                self.resolve_table_multiple_field_batch(&field),
758            );
759        }
760
761        let mut tree_data = object! {};
762        let tree_fields = self.tree_fields.clone();
763        let mut tree_keys: Vec<(String, String)> = vec![];
764        for item in self.data.members() {
765            for field in tree_fields.iter() {
766                let key = item[field].as_str().unwrap_or("");
767                if !key.is_empty() {
768                    tree_keys.push((field.clone(), key.to_string()));
769                }
770            }
771        }
772        for (field, key) in tree_keys {
773            self.resolve_tree_field(&field, &mut tree_data, &key);
774        }
775
776        for item in self.data.members_mut() {
777            let children = self
778                .db
779                .table(&self.main_table)
780                .where_and(pid_field, "=", item["id"].clone())
781                .count();
782            if children.is_empty() {
783                item["isLeaf"] = true.into();
784            }
785
786            for field in self.table_fields.iter() {
787                let key = item[field].as_str().unwrap_or("");
788                if key.is_empty() {
789                    continue;
790                }
791                if let Some(lookup) = table_lookups.get(field.as_str()) {
792                    if lookup.has_key(key) {
793                        item[field] = lookup[key].clone();
794                    }
795                }
796            }
797            for field in tree_fields.iter() {
798                let key = item[field].as_str().unwrap_or("");
799                if key.is_empty() {
800                    continue;
801                }
802                if tree_data.has_key(field) && tree_data[field].has_key(key) {
803                    item[field] = tree_data[field][key].clone();
804                }
805            }
806            for field in self.table_multiple_fields.iter() {
807                let ids = item[field].clone();
808                if !ids.is_array() || ids.is_empty() {
809                    item[field] = array![];
810                    continue;
811                }
812                let mut result = array![];
813                if let Some(lookup) = multiple_lookups.get(field.as_str()) {
814                    for id_val in ids.members() {
815                        let key = id_val.as_str().unwrap_or("");
816                        if !key.is_empty() && lookup.has_key(key) {
817                            let _ = result.push(lookup[key].clone());
818                        }
819                    }
820                }
821                item[field] = result;
822            }
823        }
824    }
825    fn columns(&mut self) -> JsonValue {
826        let mut all_fields = self.all_fields_map.clone();
827
828        for (_, item) in all_fields.entries_mut() {
829            item["name"] = item["field"].clone();
830            item["align"] = "center".into();
831            item["label"] = item["title"].clone();
832
833            if item["field"].as_str().unwrap_or("") != "id" {
834                item["sortable"] = true.into();
835            }
836            item["dataIndex"] = item["field"].clone();
837            item["slotName"] = item["field"].clone();
838            item["titleSlotName"] = item["field"].clone();
839            match item["mode"].as_str().unwrap_or_default() {
840                "string" | "text" => {
841                    item["ellipsis"] = true.into();
842                    item["tooltip"] = true.into();
843                }
844                "key" => {
845                    item["width"] = 280.into();
846                    item["ellipsis"] = true.into();
847                }
848                _ => {}
849            }
850        }
851        all_fields
852    }
853    pub fn get_table(&mut self) -> JsonValue {
854        self.db.table(&self.main_table);
855        self.db_fields();
856        self.db_search();
857        self.db_where();
858        self.db_join();
859        self.db_total();
860        self.db_order();
861        self.db.page(self.page as i32, self.limit as i32);
862
863        self.data = self.db.select();
864        self.db_table();
865
866        object! {
867            "pages"=>self.pages,
868            "total"=>self.total,
869            "data"=>self.data.clone(),
870            "columns"=>self.columns(),
871            "filter_fields"=>self.filter_fields.clone(),
872            "search_name"=>self.search_name.clone(),
873            "total_fields"=>self.total_fields.clone(),
874            "btn_all"=>array![],
875            "btn_api"=>array![],
876            "btn_ids"=>array![]
877        }
878    }
879    pub fn get_table_menu(&mut self, label_field: &str) -> JsonValue {
880        self.db.table(&self.main_table);
881        self.db_fields();
882        self.db_search();
883        self.db_where();
884        self.db_join();
885        self.db_total();
886        self.db_order();
887        self.db.page(self.page as i32, self.limit as i32);
888
889        self.data = self.db.select();
890        self.db_table();
891
892        object! {
893            "pages"=>self.pages,
894            "total"=>self.total,
895            "data"=>self.data.clone(),
896            "columns"=>self.columns(),
897            "filter_fields"=>self.filter_fields.clone(),
898            "search_name"=>self.search_name.clone(),
899            "total_fields"=>self.total_fields.clone(),
900            "btn_all"=>array![],
901            "btn_api"=>array![],
902            "btn_ids"=>array![],
903            "label_field"=>label_field
904        }
905    }
906
907    pub fn get_tree(&mut self, pid_field: &str) -> JsonValue {
908        self.db.table(&self.main_table);
909        if self.search.is_empty() || !self.pid_id.is_empty() {
910            self.db
911                .where_and(pid_field, "=", self.pid_id.clone().into());
912        }
913        self.db_fields();
914        self.db_search();
915        self.db_where();
916        self.db_join();
917        self.db_total();
918        self.db_order();
919        if self.pid_id.is_empty() {
920            self.db.page(self.page as i32, self.limit as i32);
921        } else {
922            self.db.page(1, 1000);
923        }
924
925        self.data = self.db.select();
926        self.db_table_tree(pid_field);
927
928        object! {
929            "pages"=>self.pages,
930            "total"=>self.total,
931            "data"=>self.data.clone(),
932            "columns"=>self.columns(),
933            "filter_fields"=>self.filter_fields.clone(),
934            "search_name"=>self.search_name.clone(),
935            "total_fields"=>self.total_fields.clone(),
936            "btn_all"=>array![],
937            "btn_api"=>array![],
938            "btn_ids"=>array![]
939        }
940    }
941    pub fn get_table_edit(&mut self) -> JsonValue {
942        self.db.table(&self.main_table);
943        self.db_fields();
944        self.db_search();
945        self.db_where();
946        self.db_total();
947        self.db_order();
948        self.db.page(self.page as i32, self.limit as i32);
949        self.db_join();
950        self.data = self.db.select();
951
952        object! {
953            "pages"=>self.pages,
954            "total"=>self.total,
955            "data"=>self.data.clone(),
956            "columns"=>self.columns(),
957            "edit_fields"=>self.edit_fields.clone(),
958        }
959    }
960    pub fn get_table_select(&mut self) -> JsonValue {
961        self.db.table(&self.main_table);
962        if !self.primary_key.eq("id") {
963            self.fields_keys.remove(0);
964        }
965        if !self.value.is_empty() && self.search.is_empty() {
966            let _ = self
967                .where_or
968                .push(array![self.primary_key.clone(), "in", self.value.clone()]);
969            let _ = self
970                .where_or
971                .push(array![self.primary_key.clone(), "isnot", "NULL"]);
972            let _ = self.order.push(array![
973                format!(
974                    "{} in ('{}')",
975                    self.primary_key.clone(),
976                    self.value.join("','")
977                ),
978                true
979            ]);
980        }
981        self.db_fields();
982        self.db_search();
983        self.db_where();
984        self.db_join();
985        self.db_total();
986        self.db_order();
987        self.db.page(self.page as i32, self.limit as i32);
988
989        let mut list = self.db.select();
990
991        for item in list.members_mut() {
992            let value = item[self.primary_key.clone()].clone();
993            if self.primary_key.eq("id") {
994                item.remove(&self.primary_key.clone());
995            }
996            let label = item
997                .entries()
998                .map(|(_, v)| v.to_string())
999                .collect::<Vec<String>>();
1000            let _ = self.data.push(object! {
1001                value: value,
1002                label: label.join(" | ").clone(),
1003            });
1004        }
1005
1006        object! {
1007            "pages"=>self.pages,
1008            "total"=>self.total,
1009            "data"=>self.data.clone(),
1010        }
1011    }
1012    pub fn get_table_select_tree(&mut self, pid_field: &str, label_field: &str) -> JsonValue {
1013        self.fields_keys.push(pid_field.to_string());
1014        self.db.table(&self.main_table);
1015        self.db
1016            .where_and(pid_field, "=", self.pid_id.clone().into());
1017
1018        self.db_fields();
1019        self.db_search();
1020        self.db_where();
1021        self.db_join();
1022        self.db_order();
1023        self.db.page(1, 1000);
1024
1025        self.data = self.db.select();
1026
1027        for item in self.data.members_mut() {
1028            let children = self
1029                .db
1030                .table(&self.main_table)
1031                .where_and(pid_field, "=", item["id"].clone())
1032                .count();
1033            if children.is_empty() {
1034                item["lazy"] = false.into();
1035                item["isLeaf"] = true.into();
1036            } else {
1037                item["lazy"] = true.into();
1038            }
1039        }
1040
1041        if self.pid_id.is_empty() {
1042            for id in self.value.clone() {
1043                let mut list = vec![];
1044                let mut find = self
1045                    .db
1046                    .table(&self.main_table)
1047                    .where_and("id", "=", id.into())
1048                    .field(self.fields_keys.join(",").as_str())
1049                    .find();
1050                loop {
1051                    let pid = find[pid_field].to_string();
1052                    if pid.is_empty() {
1053                        break;
1054                    }
1055                    find = self
1056                        .db
1057                        .table(&self.main_table)
1058                        .where_and("id", "=", pid.into())
1059                        .field(self.fields_keys.join(",").as_str())
1060                        .find();
1061                    list.insert(0, find.clone());
1062                }
1063                let data = &mut self.data.clone();
1064                self.tree_data(data, list.into(), 0, pid_field);
1065                self.data = data.clone();
1066            }
1067        }
1068        object! {
1069            "data"=> self.data.clone(),
1070            "label_field"=>label_field.to_string(),
1071            "pid_field"=>pid_field.to_string(),
1072        }
1073    }
1074    fn tree_data(&mut self, data: &mut JsonValue, list: JsonValue, index: usize, pid_field: &str) {
1075        let id = list[index]["id"].clone();
1076        for item in data.members_mut() {
1077            let children = self
1078                .db
1079                .table(&self.main_table)
1080                .where_and(pid_field, "=", item["id"].clone())
1081                .field(self.fields_keys.join(",").as_str())
1082                .select();
1083            if children.is_empty() {
1084                item["isLeaf"] = true.into();
1085            }
1086            if id == item["id"] && !children.is_empty() {
1087                item["children"] = children;
1088                self.tree_data(&mut item["children"], list.clone(), index + 1, pid_field);
1089            }
1090        }
1091    }
1092}