use crate::request::{ContentType, Method, Request};
use crate::{CONFIG, GLOBAL_DATA, PLUGIN_TOOLS};
use crate::{ApiResponse, Tools};
use br_fields::Field;
use json::{array, object, JsonValue};
use std::any::type_name;
use std::collections::HashMap;

/// 功能接口
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" => {
                        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" | "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;
    fn params_table_select(&mut self, mut params: JsonValue) -> JsonValue {
        params["page"] = br_fields::int::Int::new(false, "page", "页数", 10, 1).example(1.into()).field();
        params["limit"] = br_fields::int::Int::new(false, "limit", "行数", 10, 10).example(10.into()).field();
        params["search"] = br_fields::str::Str::new(false, "search", "搜索", 200, "").example("".into()).field();
        params["where_or"] = br_fields::text::Array::new(false, "where_or", "查询条件", array![]).example(array![]).field();
        params["where_and"] = br_fields::text::Array::new(false, "where_and", "查询条件", array![]).example(array![]).field();
        params["params"] = br_fields::text::Object::new(false, "params", "关联数据参数", object! {}).example(object! {}).field();
        params["field"] = br_fields::str::Str::new(false, "field", "显示字段", 50, "id").example("id".into()).field();
        params
    }
    #[cfg(any(feature = "sqlite", feature = "mssql", feature = "mysql", feature = "pgsql"))]
    fn table_select(
        &mut self,
        request: JsonValue,
        table_name: &str,
        fields: Vec<&str>,
    ) -> JsonValue {
        let page = request["page"].as_i32().unwrap_or(1);
        let limit = request["limit"].as_i32().unwrap_or(10);

        let search = request["search"].as_str().unwrap_or("");

        let field_id = request["field"].as_str().unwrap_or("id");

        let where_or = request["where_or"].clone();
        let where_and = request["where_and"].clone();

        let mut tools = self.tools();
        let db = tools.db.table(table_name);

        if !search.is_empty() {
            db.where_and(&fields.join("|"), "like", format!("%{search}%").into());
        }

        for (key, value) in where_or.entries() {
            if value.is_empty() {
                continue;
            }
            if value.is_array() {
                db.where_or(key, "between", value.clone());
                db.where_or(key, "in", value.clone());
            } else if value.is_boolean() {
                db.where_or(key, "=", value.clone());
            } else {
                db.where_or(key, "like", format!("%{value}%").into());
            }
        }

        for value in where_and.members() {
            db.where_and(
                value[0].as_str().unwrap(),
                value[1].as_str().unwrap(),
                value[2].clone(),
            );
        }

        let total = (db.clone().count().as_f64().unwrap() / f64::from(limit)).ceil() as i64;
        let mut db_list = db.clone();

        db_list.field(format!("{},{}", field_id, fields.join(",")).as_str());

        let mut data = db_list.page(page, limit).select();
        let mut list = array![];
        for item in data.members_mut() {
            let value = item[field_id].clone();
            item.remove(field_id);

            let label = item.entries().map(|(_, v)| v.to_string()).collect::<Vec<String>>();

            list.push(object! {
                value: value,
                label: label.join(" | ").clone(),
            }).unwrap();
        }
        object! {
            total:total,
            data:list,
        }
    }
    /// 菜单表格接收参数
    fn params_table_menu(&mut self, mut params: JsonValue) -> JsonValue {
        params["search"] = br_fields::str::Str::new(false, "search", "搜索", 200, "").example("".into()).field();
        params["where_or"] = br_fields::text::Array::new(false, "where_or", "查询条件", array![]).example(array![]).field();
        params["where_and"] = br_fields::text::Array::new(false, "where_and", "查询条件", array![]).example(array![]).field();
        params
    }
    #[allow(clippy::too_many_arguments)]
    #[cfg(any(feature = "sqlite", feature = "mssql", feature = "mysql", feature = "pgsql"))]
    fn table_menu(
        &mut self,
        request: JsonValue,
        table_name: &str,
        label_field: &str,
        fields: JsonValue,

        hidd_field: Vec<&str>,
        show_field: Vec<&str>,

        search_fields: Vec<&str>,
        _filter_fields: Vec<&str>,
    ) -> JsonValue {
        let search = request["search"].as_str().unwrap_or("");

        let order = request["order"].clone();
        let where_or = request["where_or"].clone();
        let where_and = request["where_and"].clone();
        let mut columns = array![];
        let mut search_name = vec![];
        let mut search_field = vec![];
        let mut filter_columns = vec![];
        let mut table_fields = object! {};
        let mut table_field_json = vec![];

        let mut alls_field = fields.entries().map(|(x, _)| x).collect::<Vec<&str>>();
        alls_field.retain(|x| !hidd_field.contains(x));
        if !show_field.is_empty() {
            alls_field.retain(|x| show_field.contains(x) || *x == "id");
        }

        for item in alls_field.iter() {
            let row = &fields[item.to_string()];
            let field = row["field"].to_string();
            let title = row["title"].to_string();
            let mode = row["mode"].to_string();

            if search_fields.contains(&field.as_str()) {
                search_name.push(title);
                search_field.push(field.clone());
            }
            filter_columns.push(self.filter_column(row.clone()));
            columns.push(self.table_column(row.clone())).unwrap();
            let mut table_field_info = object! {};
            match mode.as_str() {
                "table" => table_field_info = row.clone(),
                "array" => table_field_json.push(field.clone()),
                _ => {}
            }
            if !table_field_info.is_empty() {
                table_fields[field.as_str()] = table_field_info;
            }
        }

        let mut tools = self.tools();
        let db = tools.db.table(table_name);

        if !search.is_empty() {
            db.where_and(
                &search_field.join("|"),
                "like",
                format!("%{search}%").into(),
            );
        }

        for (key, value) in where_or.entries() {
            if value.is_empty() {
                continue;
            }
            if value.is_array() {
                db.where_or(key, "between", value.clone());
                db.where_or(key, "in", value.clone());
            } else if value.is_boolean() {
                db.where_or(key, "=", value.clone());
            } else {
                db.where_or(key, "like", format!("%{value}%").into());
            }
        }

        for value in where_and.members() {
            db.where_and(
                value[0].as_str().unwrap(),
                value[1].as_str().unwrap(),
                value[2].clone(),
            );
        }

        let mut db_list = db.clone();

        for item in order.members() {
            db_list.order(item[0].as_str().unwrap(), item[1].as_bool().unwrap());
        }

        let t = alls_field.join(",");
        db_list.field(t.as_str());

        if !table_field_json.is_empty() {
            db_list.json(&table_field_json.join(","));
        }

        let mut data = db_list.select();

        let mut table_datas = object! {};
        let mut ids = HashMap::new();

        for item in data.members_mut() {
            for (field, _) in table_fields.entries() {
                if table_datas[field].is_empty() {
                    table_datas[field] = array![];
                }
                let _ = table_datas[field].push(item[field].clone());
            }
        }
        for (field, info) in table_fields.entries_mut() {
            let _ = info["fields"].push("id");
            let fields_k = info["fields"].members().map(|x| x.as_str().unwrap()).collect::<Vec<&str>>();
            let table_name = info["table"].clone();
            let mut data_list = self.tools().db.table(table_name.as_str().unwrap()).where_and("id", "in", table_datas[field].clone()).field(&fields_k.join(",")).select();

            for item in data_list.members_mut() {
                let id = item["id"].as_str().unwrap_or("").to_string();
                item.remove("id");
                let label = item.entries().map(|(_, v)| v.as_str().unwrap()).collect::<Vec<&str>>();
                ids.insert(
                    id.clone(),
                    object! {
                        value: id.clone(),
                        label:label.join(" | ").clone(),
                    },
                );
            }
        }

        for item in data.members_mut() {
            for (field, _) in table_fields.entries() {
                if item[field].is_empty() {
                    continue;
                }
                item[field] = ids[item[field].as_str().unwrap()].clone();
            }
        }

        object! {
            data:data,
            columns:columns,
            search_name:search_name.join("/"),
            filter_columns:filter_columns,
            label_field:label_field,
            btn_all:array![],
            btn_api:array![]
        }
    }
    /// 树型表格接收参数
    fn params_table_tree(&mut self, mut params: JsonValue) -> JsonValue {
        params["pid"] = br_fields::str::Str::new(false, "pid", "上级ID", 50, "").example("".into()).field();
        params["search"] = br_fields::str::Str::new(false, "search", "搜索", 200, "").example("".into()).field();
        params["where_or"] = br_fields::text::Array::new(false, "where_or", "查询条件", array![]).example(array![]).field();
        params["where_and"] = br_fields::text::Array::new(false, "where_and", "查询条件", array![]).example(array![]).field();
        params
    }
    #[allow(clippy::too_many_arguments)]
    #[cfg(any(feature = "sqlite", feature = "mssql", feature = "mysql", feature = "pgsql"))]
    fn table_tree(
        &mut self,
        request: JsonValue,
        table_name: &str,
        pid_field: &str,
        label_field: &str,
        fields: JsonValue,
        hidd_field: Vec<&str>,
        show_field: Vec<&str>,
        search_fields: Vec<&str>,
        _filter_fields: Vec<&str>,
    ) -> JsonValue {
        let search = request["search"].as_str().unwrap_or("");

        let pid = request["pid"].clone();

        let order = request["order"].clone();
        let where_or = request["where_or"].clone();
        let where_and = request["where_and"].clone();
        let mut columns = array![];
        let mut search_name = vec![];
        let mut search_field = vec![];
        let mut filter_columns = vec![];
        let mut table_field_json = vec![];
        let mut table_fields = object! {};

        let mut alls_field = fields.entries().map(|(x, _)| x).collect::<Vec<&str>>();
        alls_field.retain(|x| !hidd_field.contains(x));
        if !show_field.is_empty() {
            alls_field.retain(|x| show_field.contains(x) || *x == "id");
        }

        for item in alls_field.iter() {
            let row = fields[item.to_string()].clone();
            let field = row["field"].to_string();
            let title = row["title"].to_string();
            let mode = row["mode"].to_string();

            if search_fields.contains(&field.as_str()) {
                search_name.push(title);
                search_field.push(field.clone());
            }
            filter_columns.push(self.filter_column(row.clone()));
            columns.push(self.table_column(row.clone())).unwrap();
            let mut table_field_info = object! {};
            match mode.as_str() {
                "table" => table_field_info = row.clone(),
                "array" => table_field_json.push(field.clone()),
                _ => {}
            }
            if !table_field_info.is_empty() {
                table_fields[field.as_str()] = table_field_info;
            }
        }

        let mut tools = self.tools();
        let db = tools.db.table(table_name);
        db.where_and(pid_field, "=", pid);
        if !search.is_empty() {
            db.where_and(
                &search_field.join("|"),
                "like",
                format!("%{search}%").into(),
            );
        }

        for (key, value) in where_or.entries() {
            if value.is_empty() {
                continue;
            }
            if value.is_array() {
                // db.where_or(key, "between", value.clone());
                db.where_or(key, "in", value.clone());
            } else if value.is_boolean() {
                db.where_or(key, "=", value.clone());
            } else {
                db.where_or(key, "like", format!("%{value}%").into());
            }
        }

        for value in where_and.members() {
            db.where_and(
                value[0].as_str().unwrap(),
                value[1].as_str().unwrap(),
                value[2].clone(),
            );
        }

        let mut db_list = db.clone();

        for item in order.members() {
            db_list.order(item[0].as_str().unwrap(), item[1].as_bool().unwrap());
        }
        let t = alls_field.join(",");
        db_list.field(t.as_str());
        if !table_field_json.is_empty() {
            db_list.json(&table_field_json.join(","));
        }
        let mut data = db_list.select();

        let mut table_datas = object! {};
        let mut ids = HashMap::new();

        for item in data.members_mut() {
            for (field, _) in table_fields.entries() {
                if table_datas[field].is_empty() {
                    table_datas[field] = array![];
                }
                let _ = table_datas[field].push(item[field].clone());
            }
        }
        for (field, info) in table_fields.entries_mut() {
            let _ = info["fields"].push("id");
            let fields_k = info["fields"].members().map(|x| x.as_str().unwrap()).collect::<Vec<&str>>();
            let table_name = info["table"].clone();
            let mut data_list = self.tools().db.table(table_name.as_str().unwrap()).where_and("id", "in", table_datas[field].clone()).field(&fields_k.join(",")).select();

            for item in data_list.members_mut() {
                let id = item["id"].as_str().unwrap_or("").to_string();
                item.remove("id");
                let label = item.entries().map(|(_, v)| v.as_str().unwrap()).collect::<Vec<&str>>();
                ids.insert(
                    id.clone(),
                    object! {
                        value: id.clone(),
                        label:label.join(" | ").clone(),
                    },
                );
            }
        }

        let mut list = array![];
        for item in data.members_mut() {
            for (field, _) in table_fields.entries() {
                if item[field].is_empty() {
                    continue;
                }
                item[field] = ids[item[field].as_str().unwrap()].clone();
            }
            let _ = list.push(object! {
                id:item["id"].as_str().unwrap(),
                code:item["code"].as_str().unwrap(),
                label:item[label_field].as_str().unwrap(),
                data:item.clone(),
            });
        }

        object! {
            data:list,
            columns:columns,
            search_name:search_name.join("/"),
            filter_columns:filter_columns,
            pid_field:pid_field,
            btn_all:array![],
            btn_api:array![]
        }
    }
    /// 表格接收参数
    fn params_table_list(&mut self, mut params: JsonValue) -> JsonValue {
        params["page"] = br_fields::int::Int::new(false, "page", "页数", 10, 1).example(1.into()).field();
        params["limit"] = br_fields::int::Int::new(false, "limit", "行数", 10, 10).example(10.into()).field();
        params["search"] = br_fields::str::Str::new(false, "search", "搜索", 200, "").example("".into()).field();
        params["order"] = br_fields::text::Array::new(false, "order", "排序", array![]).example(array![array!["id", false]]).field();
        params["where_or"] = br_fields::text::Array::new(false, "where_or", "查询条件", array![]).example(array![]).field();
        params["where_and"] = br_fields::text::Array::new(false, "where_and", "查询条件", array![]).example(array![]).field();
        params["field"] = br_fields::str::Str::new(false, "field", "显示字段", 20, "id").example("id".into()).field();
        params
    }
    /// 列表表格渲染
    /// * 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 {
        let page = request["page"].as_i32().unwrap_or(1);
        let limit = request["limit"].as_i32().unwrap_or(10);
        let search = request["search"].as_str().unwrap_or("");
        let order = request["order"].clone();
        let where_or = request["where_or"].clone();
        let where_and = request["where_and"].clone();
        let mut columns = array![];
        let mut search_name = vec![];
        let mut search_field = vec![];
        let mut filter_columns = vec![];

        // 关联字段
        let mut table_fields = object! {};
        // 需要处理为json格式的字段
        let mut json_fields = vec![];

        let mut alls_field = fields.entries().map(|(x, _)| x).collect::<Vec<&str>>();
        alls_field.retain(|x| !hidd_field.contains(x));
        if !show_field.is_empty() {
            alls_field.retain(|x| show_field.contains(x) || *x == "id");
        }

        for item in alls_field.iter() {
            let key = item.to_string();
            let field = fields[key.clone()]["field"].as_str().unwrap();
            let title = fields[key.clone()]["title"].as_str().unwrap();
            let mode = fields[key.clone()]["mode"].as_str().unwrap();

            if search_fields.contains(&field) {
                search_name.push(title);
                search_field.push(field);
            }
            if filter_fields.contains(&field) {
                filter_columns.push(self.filter_column(fields[key.clone()].clone()));
            }
            columns.push(self.table_column(fields[key.clone()].clone())).unwrap();

            match mode {
                "table" => {
                    let table_field_info = if mode == "table" {
                        fields[key.clone()].clone()
                    } else {
                        JsonValue::Null
                    };
                    if !table_field_info.is_empty() {
                        table_fields[field] = table_field_info;
                    }
                }
                "object" | "array" | "polygon" => {
                    json_fields.push(field);
                }
                _ => {}
            }
        }

        let mut tools = self.tools();
        let db = tools.db.table(table_name);

        if !search.is_empty() {
            db.where_and(
                &search_field.join("|"),
                "like",
                format!("%{search}%").into(),
            );
        }

        for (key, value) in where_or.entries() {
            if value.is_empty() {
                continue;
            }
            if value.is_array() {
                db.where_or(key, "in", value.clone());
            } else if value.is_boolean() {
                db.where_or(key, "=", value.clone());
            } else {
                db.where_or(key, "like", format!("%{value}%").into());
            }
        }

        for value in where_and.members() {
            db.where_and(
                value[0].as_str().unwrap(),
                value[1].as_str().unwrap(),
                value[2].clone(),
            );
        }

        let total = db.clone().count().as_f64().unwrap();
        let mut db_list = db.clone();

        for item in order.members() {
            db_list.order(item[0].as_str().unwrap(), item[1].as_bool().unwrap());
        }

        let t = alls_field.join(",");
        db_list.field(t.as_str());
        let mut data = db_list.page(page, limit).json(&json_fields.join(",")).select();

        let mut table_datas = object! {};
        let mut ids = HashMap::new();

        for item in data.members_mut() {
            if table_fields.is_empty() {
                continue;
            }
            for (field, _) in table_fields.entries() {
                if table_datas[field].is_empty() {
                    table_datas[field] = array![];
                }
                let _ = table_datas[field].push(item[field].clone());
            }
        }
        for (field, info) in table_fields.entries_mut() {
            let _ = info["fields"].push("id");
            let fields_k = info["fields"].members().map(|x| x.as_str().unwrap()).collect::<Vec<&str>>();
            let table_name = info["table"].clone();
            let mut data_list = self.tools().db.table(table_name.as_str().unwrap()).where_and("id", "in", table_datas[field].clone()).field(&fields_k.join(",")).select();

            for item in data_list.members_mut() {
                let id = item["id"].as_str().unwrap_or("").to_string();
                item.remove("id");
                let label = item.entries().map(|(_, v)| v.to_string()).collect::<Vec<String>>();
                ids.insert(
                    id.clone(),
                    object! {
                        value: id.clone(),
                        label:label.join(" | ").clone(),
                    },
                );
            }
        }

        for item in data.members_mut() {
            if table_fields.is_empty() {
                continue;
            }
            for (field, _) in table_fields.entries() {
                if item[field].is_empty() {
                    continue;
                }
                let key = item[field].as_str().unwrap_or("");
                if key.is_empty() {
                    continue;
                }
                if !ids.contains_key(key) {
                    continue;
                }
                item[field] = ids.get(key).unwrap().clone();
            }
        }

        object! {
            total:total,
            data:data,
            columns:columns,
            search_name:search_name.join("/"),
            filter_columns:filter_columns,
            btn_all:array![],
            btn_api:array![],
            btn_ids:array![]
        }
    }
    fn table_column(&mut self, field: JsonValue) -> JsonValue {
        object! {
            name:field["field"].clone(),
            label:field["title"].clone(),
            align:"center",
            field:field["field"].clone(),
            sortable:true,
            mode:field["mode"].clone(),
            dec:field["dec"].clone(),
            fields:field["fields"].clone()
        }
    }
    fn filter_column(&mut self, field: JsonValue) -> JsonValue {
        object! {
            name:field["field"].clone(),
            label:field["title"].clone(),
            mode:field["mode"].clone(),
            option:field["option"].clone(),
            api:field["api"].clone(),
            fields:field["fields"].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,
    /// 是否需要密码
    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(),
        }
    }

    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 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 {
        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:self.color.clone().str(),
            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,
}

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

/// 按钮类型
#[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,
    Blue,
    Yellow,
    Green,
}

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


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",
        }
    }
}