package com.hzya.frame.basedao.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.hzya.frame.basedao.entity.*;
import com.hzya.frame.basedao.service.GeneralService;
import com.hzya.frame.uuid.UUIDUtils;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author lvleigang
 * @Description 通用service
 * @Date 9:34 上午 2022/12/7
 * @return
 **/
@Service(value = "generalServiceImpl")
public class GeneralServiceImpl implements GeneralService {

    public final static Logger log = LoggerFactory.getLogger(GeneralServiceImpl.class);
    private static final List<WhereCriterion> defaultWhereCriteria = new ArrayList<>();
    private static final List<OrderCriterion> defaultOrder = new ArrayList<>();
    private static final List<ReturnCriterion> defaultFileds = new ArrayList<>();
    private static final List<ModifyCriterion> defaultModify = new ArrayList<>();

    static {
        defaultWhereCriteria.add(new WhereCriterion("(", "lvl", ConditionType.等于.getValue(), "0", ")", ConnectType.AND));
        defaultWhereCriteria.add(new WhereCriterion("(", "sts", ConditionType.等于.getValue(), "Y", ")", ConnectType.AND));
        defaultOrder.add(new OrderCriterion("sorts", "ASC"));
        defaultFileds.add(new ReturnCriterion("id", "id"));
        defaultFileds.add(new ReturnCriterion("up_id", "up_id"));
        defaultModify.add(new ModifyCriterion("sts", "N"));
    }

    @Autowired
    private BaseDaoUtilImpl baseDaoUtilImpl;

    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 查询list
     * @Date 9:40 上午 2022/12/7
     **/
    @Override
    public JsonResultEntity selectList(JSONObject jsonObject) {
        //校验表名
        if (!checkStr(jsonObject.getString("tableName"))) {
            return BaseResult.getFailureMessageEntity("表名不存在");
        }
        String tablename = jsonObject.getString("tableName");
        if (!checkStr(jsonObject.getString("jsonStr"))) {
            return BaseResult.getFailureMessageEntity("请求数据不存在");
        }
        String jsonStr = jsonObject.getString("jsonStr");
        RequestDisposeEntity requestDisposeEntity = JSONObject.parseObject(jsonStr, RequestDisposeEntity.class);
        if (requestDisposeEntity == null) {
            return BaseResult.getFailureMessageEntity("请求数据不存在");
        }
        List<ReturnCriterion> fileds = requestDisposeEntity.getReturnCriterions();
        List<WhereCriterion> wheres = requestDisposeEntity.getWheres();
        if (wheres == null) {
            wheres = new ArrayList<>();
        }
        wheres.add(new WhereCriterion("(", "sts", ConditionType.等于.getValue(), "Y", ")", ConnectType.AND));
        List<OrderCriterion> order = requestDisposeEntity.getOrder();
        List<HashMap<String, Object>> list = null;
        try {
            list = baseDaoUtilImpl.selectList(tablename, order, fileds, wheres);
            return BaseResult.getSuccessMessageEntity("查询成功", list);
        } catch (Exception e) {
            log.error("default：selectList{}", e.getMessage());
            return BaseResult.getFailureMessageEntity("查询失败");
        }
    }

    @Override
    public JsonResultEntity selectListSimple(JSONObject jsonObject) {
        //校验表名
        if (!checkStr(jsonObject.getString("tableName"))) {
            return BaseResult.getFailureMessageEntity("表名不存在");
        }
        String tablename = jsonObject.getString("tableName");
        if (!checkStr(jsonObject.getString("jsonStr"))) {
            return BaseResult.getFailureMessageEntity("请求数据不存在");
        }
        JSONObject queryJson = jsonObject.getJSONObject("jsonStr");
        List<WhereCriterion> wheres = new ArrayList<>();
        wheres.add(new WhereCriterion("(", "sts", ConditionType.等于.getValue(), "Y", ")", ConnectType.AND));
        List<OrderCriterion> order = new ArrayList<>();
        order.add(new OrderCriterion("sorts", "ASC"));
        if (queryJson != null) {
            JSONObject stringsJson = queryJson.getJSONObject("strings");
            JSONObject dateJson = queryJson.getJSONObject("date");
            if (stringsJson != null) {
                Map<String, Object> stringsMap = stringsJson.getInnerMap();
                if (!stringsMap.isEmpty()) {
                    for (Map.Entry<String, Object> stringObjectEntry : stringsMap.entrySet()) {
                        wheres.add(new WhereCriterion("(", stringObjectEntry.getKey(), ConditionType.包含.getValue(), stringObjectEntry.getValue(), ")", ConnectType.AND));
                    }
                }
            }
            if (dateJson != null) {
                Map<String, Object> dateMap = dateJson.getInnerMap();
                if (!dateMap.isEmpty()) {
                    for (Map.Entry<String, Object> dateObjectEntry : dateMap.entrySet()) {
                        JSONObject json = (JSONObject) dateObjectEntry.getValue();
                        if (json.getString("start") != null
                                && !"".equals(json.getString("start"))
                                && json.getString("end") != null
                                && !"".equals(json.getString("end"))) {
                            wheres.add(new WhereCriterion("(", dateObjectEntry.getKey(), ConditionType.介于.getValue(), json.getString("start"), json.getString("end"), ")", ConnectType.AND));
                        } else if (json.getString("end") != null
                                && !"".equals(json.getString("end"))) {
                            wheres.add(new WhereCriterion("(", dateObjectEntry.getKey(), ConditionType.小于等于.getValue(), json.getString("end"), ")", ConnectType.AND));
                        } else if (json.getString("start") != null
                                && !"".equals(json.getString("start"))) {
                            wheres.add(new WhereCriterion("(", dateObjectEntry.getKey(), ConditionType.大于等于.getValue(), json.getString("start"), ")", ConnectType.AND));
                        }
                    }
                }
            }
        }
        List<HashMap<String, Object>> list = null;
        try {
            list = baseDaoUtilImpl.selectWhereList(tablename, order, wheres);
            return BaseResult.getSuccessMessageEntity("查询成功", list);
        } catch (Exception e) {
            log.error("default：selectListSimple{}", e.getMessage());
            return BaseResult.getFailureMessageEntity("查询失败");
        }
    }

    @Override
    public JsonResultEntity selectPageSimple(JSONObject jsonObject) {
        //校验表名
        if (!checkStr(jsonObject.getString("tableName"))) {
            return BaseResult.getFailureMessageEntity("表名不存在");
        }
        String tablename = jsonObject.getString("tableName");
        if (!checkStr(jsonObject.getString("jsonStr"))) {
            return BaseResult.getFailureMessageEntity("请求数据不存在");
        }
        JSONObject queryJson = jsonObject.getJSONObject("jsonStr");
        Integer pageNum = queryJson.getInteger("pageNum");
        Integer pageSize = queryJson.getInteger("pageSize");
        if (pageNum == null || pageSize == null) {
            return BaseResult.getFailureMessageEntity("查询请求参数不存在");
        }
        List<WhereCriterion> wheres = new ArrayList<>();
        wheres.add(new WhereCriterion("(", "sts", ConditionType.等于.getValue(), "Y", ")", ConnectType.AND));
        List<OrderCriterion> order = new ArrayList<>();
        order.add(new OrderCriterion("sorts", "ASC"));
        if (queryJson != null) {
            JSONObject stringsJson = queryJson.getJSONObject("strings");
            JSONObject dateJson = queryJson.getJSONObject("date");
            if (stringsJson != null) {
                Map<String, Object> stringsMap = stringsJson.getInnerMap();
                if (!stringsMap.isEmpty()) {
                    for (Map.Entry<String, Object> stringObjectEntry : stringsMap.entrySet()) {
                        wheres.add(new WhereCriterion("(", stringObjectEntry.getKey(), ConditionType.包含.getValue(), stringObjectEntry.getValue(), ")", ConnectType.AND));
                    }
                }
            }
            if (dateJson != null) {
                Map<String, Object> dateMap = dateJson.getInnerMap();
                if (!dateMap.isEmpty()) {
                    for (Map.Entry<String, Object> dateObjectEntry : dateMap.entrySet()) {
                        JSONObject json = (JSONObject) dateObjectEntry.getValue();
                        if (json.getString("start") != null
                                && !"".equals(json.getString("start"))
                                && json.getString("end") != null
                                && !"".equals(json.getString("end"))) {
                            wheres.add(new WhereCriterion("(", dateObjectEntry.getKey(), ConditionType.介于.getValue(), json.getString("start"), json.getString("end"), ")", ConnectType.AND));
                        } else if (json.getString("end") != null
                                && !"".equals(json.getString("end"))) {
                            wheres.add(new WhereCriterion("(", dateObjectEntry.getKey(), ConditionType.小于等于.getValue(), json.getString("end"), ")", ConnectType.AND));
                        } else if (json.getString("start") != null
                                && !"".equals(json.getString("start"))) {
                            wheres.add(new WhereCriterion("(", dateObjectEntry.getKey(), ConditionType.大于等于.getValue(), json.getString("start"), ")", ConnectType.AND));
                        }
                    }
                }
            }
        }
        PageInfo pageInfo = null;
        try {
            pageInfo = baseDaoUtilImpl.selectWherePage(tablename, order, wheres, pageNum, pageSize);
            return BaseResult.getSuccessMessageEntity("查询成功", pageInfo);
        } catch (Exception e) {
            log.error("default：selectPageSimple{}", e.getMessage());
            return BaseResult.getFailureMessageEntity("查询失败");
        }
    }

    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 查询page
     * @Date 9:40 上午 2022/12/7
     **/
    @Override
    public JsonResultEntity selectPage(JSONObject jsonObject) {
        //校验表名
        if (!checkStr(jsonObject.getString("tableName"))) {
            return BaseResult.getFailureMessageEntity("表名不存在");
        }
        String tablename = jsonObject.getString("tableName");
        if (!checkStr(jsonObject.getString("jsonStr"))) {
            return BaseResult.getFailureMessageEntity("请求数据不存在");
        }
        String jsonStr = jsonObject.getString("jsonStr");
        RequestDisposeEntity requestDisposeEntity = JSONObject.parseObject(jsonStr, RequestDisposeEntity.class);
        if (requestDisposeEntity == null) {
            return BaseResult.getFailureMessageEntity("请求数据不存在");
        }
        List<ReturnCriterion> fileds = requestDisposeEntity.getReturnCriterions();
        List<WhereCriterion> wheres = requestDisposeEntity.getWheres();
        List<OrderCriterion> order = requestDisposeEntity.getOrder();
        PageInfo pageInfo = null;
        try {
            pageInfo = baseDaoUtilImpl.selectPage(tablename, order, fileds, wheres, requestDisposeEntity.getPageNum(), requestDisposeEntity.getPageSize());
            return BaseResult.getSuccessMessageEntity("查询成功", pageInfo);
        } catch (Exception e) {
            log.error("default：selectPage{}", e.getMessage());
            return BaseResult.getFailureMessageEntity("查询失败");
        }
    }

    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 添加
     * @Date 9:40 上午 2022/12/7
     **/
    @Override
    public JsonResultEntity inster(JSONObject jsonObject) {
        //校验表名
        if (!checkStr(jsonObject.getString("tableName"))) {
            return BaseResult.getFailureMessageEntity("表名不存在");
        }
        String tablename = jsonObject.getString("tableName");
        if (!checkStr(jsonObject.getString("jsonStr"))) {
            return BaseResult.getFailureMessageEntity("请求数据不存在");
        }
        String jsonStr = jsonObject.getString("jsonStr");
        RequestDisposeEntity requestDisposeEntity = JSONObject.parseObject(jsonStr, RequestDisposeEntity.class);
        RequestDisposeEntity requestDisposeEntity1 = JSONObject.parseObject(jsonStr, RequestDisposeEntity.class);
        if (requestDisposeEntity == null) {
            return BaseResult.getFailureMessageEntity("请求数据不存在");
        }
        List<ModifyCriterion> modifyExamples = requestDisposeEntity.getModifys();
        modifyExamples.add(new ModifyCriterion("id", UUIDUtils.getUUID()));
        if (modifyExamples != null && modifyExamples.size() > 0) {
            try {
                Integer i = baseDaoUtilImpl.insterOne(tablename, modifyExamples);
                return BaseResult.getSuccessMessageEntity("保存成功");
            } catch (Exception e) {
                log.error("default：inster{}", e.getMessage());
                return BaseResult.getFailureMessageEntity("保存失败");
            }
        } else {
            return BaseResult.getFailureMessageEntity("保存字段为空");
        }
    }

    //public static void main(String[] args) {
    //    String a = "";
    //
    //}


    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 添加list
     * @Date 9:41 上午 2022/12/7
     **/
    @Override
    public JsonResultEntity insterList(JSONObject jsonObject) {
        //校验表名
        if (!checkStr(jsonObject.getString("tableName"))) {
            return BaseResult.getFailureMessageEntity("表名不存在");
        }
        String tablename = jsonObject.getString("tableName");
        if (!checkStr(jsonObject.getString("jsonStr"))) {
            return BaseResult.getFailureMessageEntity("请求数据不存在");
        }
        String jsonStr = jsonObject.getString("jsonStr");
        RequestDisposeEntity requestDisposeEntity = JSONObject.parseObject(jsonStr, RequestDisposeEntity.class);
        if (requestDisposeEntity == null) {
            return BaseResult.getFailureMessageEntity("请求数据不存在");
        }
        List<List<ModifyCriterion>> modifyExamples = requestDisposeEntity.getBatchModifys();
        List<String> batchFiled = requestDisposeEntity.getBatchFileds();
        List<String> sqlbatchFiled = new ArrayList<>();
        sqlbatchFiled.add("id");
        sqlbatchFiled.addAll(batchFiled);
        if (modifyExamples != null && modifyExamples.size() > 0 && batchFiled != null && batchFiled.size() > 0) {
            List<List<ModifyCriterion>> sqlmodifyExamples = new ArrayList<>();
            for (int i = 0; i < modifyExamples.size(); i++) {
                List<ModifyCriterion> modifyCriteria = new ArrayList<>();
                modifyCriteria.add(new ModifyCriterion("id", UUIDUtils.getUUID()));
                modifyCriteria.addAll(modifyExamples.get(i));
                sqlmodifyExamples.add(modifyCriteria);
            }
            try {
                Integer i = baseDaoUtilImpl.insterList(tablename, sqlbatchFiled, sqlmodifyExamples);
                return BaseResult.getSuccessMessageEntity("保存成功");
            } catch (Exception e) {
                log.error("default：insterList{}", e.getMessage());
                return BaseResult.getFailureMessageEntity("保存失败");
            }
        } else {
            return BaseResult.getFailureMessageEntity("批量保存字段或值为空");
        }
    }

    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 修改
     * @Date 9:41 上午 2022/12/7
     **/
    @Override
    public JsonResultEntity update(JSONObject jsonObject) {
        //校验表名
        if (!checkStr(jsonObject.getString("tableName"))) {
            return BaseResult.getFailureMessageEntity("表名不存在");
        }
        String tablename = jsonObject.getString("tableName");
        if (!checkStr(jsonObject.getString("jsonStr"))) {
            return BaseResult.getFailureMessageEntity("请求数据不存在");
        }
        String jsonStr = jsonObject.getString("jsonStr");
        RequestDisposeEntity requestDisposeEntity = JSONObject.parseObject(jsonStr, RequestDisposeEntity.class);
        if (requestDisposeEntity == null) {
            return BaseResult.getFailureMessageEntity("请求数据不存在");
        }
        List<WhereCriterion> wheres = requestDisposeEntity.getWheres();
        List<ModifyCriterion> modifyExamples = requestDisposeEntity.getModifys();
        if (modifyExamples != null && modifyExamples.size() > 0) {
            try {
                Integer i = baseDaoUtilImpl.update(tablename, modifyExamples, wheres);
                return BaseResult.getSuccessMessageEntity("修改成功");
            } catch (Exception e) {
                log.error("default：update{}", e.getMessage());
                return BaseResult.getFailureMessageEntity("修改失败");
            }
        } else {
            return BaseResult.getFailureMessageEntity("字段为空");
        }

    }

    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 删除
     * @Date 9:41 上午 2022/12/7
     **/
    @Override
    public JsonResultEntity delete(JSONObject jsonObject) {
        //校验表名
        if (!checkStr(jsonObject.getString("tableName"))) {
            return BaseResult.getFailureMessageEntity("表名不存在");
        }
        String tablename = jsonObject.getString("tableName");
        if (!checkStr(jsonObject.getString("jsonStr"))) {
            return BaseResult.getFailureMessageEntity("请求数据不存在");
        }
        String jsonStr = jsonObject.getString("jsonStr");
        RequestDisposeEntity requestDisposeEntity = JSONObject.parseObject(jsonStr, RequestDisposeEntity.class);
        if (requestDisposeEntity == null) {
            return BaseResult.getFailureMessageEntity("请求数据不存在");
        }
        List<WhereCriterion> wheres = requestDisposeEntity.getWheres();
        try {
            Integer i = baseDaoUtilImpl.delete(tablename, wheres);
            return BaseResult.getSuccessMessageEntity("删除成功");
        } catch (Exception e) {
            log.error("default：delete{}", e.getMessage());
            return BaseResult.getFailureMessageEntity("删除失败");
        }
    }

    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 查询字段
     * @Date 9:41 上午 2022/12/7
     **/
    @Override
    public JsonResultEntity defaultField(JSONObject jsonObject) {
        //校验表名
        if (!checkStr(jsonObject.getString("tableName"))) {
            return BaseResult.getFailureMessageEntity("表名不存在");
        }
        String tablename = jsonObject.getString("tableName");
        JSONObject jsonStr = jsonObject.getJSONObject("jsonStr");
        String serverName = jsonStr.getString("serverName");
        if (serverName == null || "".equals(serverName)) {
            return BaseResult.getFailureMessageEntity("请求serverName为空");
        }
        //根据服务名称查询表缓存表
        List<HashMap<String, Object>> mapList = querytableCacheByService(tablename, serverName);
        if (mapList != null && mapList.size() == 1) {
            HashMap<String, Object> map = mapList.get(0);
            if (map.get("enable_status") != null) {
                if ("1".equals(map.get("enable_status"))) {
                    List<ReturnCriterion> returnCriterionListList1 = setReturnFiled(Arrays.asList("id", "view_name", "view_filed", "datebase_name", "value_type", "show_type", "sorts"));
                    //获取返回条件，前端可以根据菜单id查询获取下级菜单，或者根据一级菜单等级获取菜单
                    List<WhereCriterion> whereList1 = new ArrayList<>();
                    WhereCriterion upIdWhereCriterion1 = new WhereCriterion("(", "table_cache_id", ConditionType.等于.getValue(), map.get("id"), "", ConnectType.AND);
                    WhereCriterion stsWhereCriterion1 = new WhereCriterion("", "sts", ConditionType.等于.getValue(), "Y", ")", ConnectType.AND);
                    whereList1.add(upIdWhereCriterion1);
                    whereList1.add(stsWhereCriterion1);
                    List<OrderCriterion> order = new ArrayList<>();
                    order.add(new OrderCriterion("sorts", "ASC"));
                    List<HashMap<String, Object>> mapList1 = baseDaoUtilImpl.selectList("sys_view_filed", order, returnCriterionListList1, whereList1);
                    if (mapList1 != null && mapList1.size() > 0) {
                        return BaseResult.getSuccessMessageEntity("查询字段成功", mapList1);
                    } else {
                        return BaseResult.getFailureMessageEntity("字段配置表为空");
                    }
                } else {
                    return BaseResult.getFailureMessageEntity("该服务已停用");
                }
            } else {
                return BaseResult.getFailureMessageEntity("表缓存表启停配置错误");
            }
        } else {
            return BaseResult.getFailureMessageEntity("表缓存表配置错误");
        }
    }


    /**
     * @param serverName
     * @return java.util.List<java.util.HashMap < java.lang.String, java.lang.Object>>
     * @Author lvleigang
     * @Description 根据服务名称查询表缓存表
     * @Date 2:59 下午 2022/12/15
     **/
    private List<HashMap<String, Object>> querytableCacheByService(String tablename, String serverName) {
        List<HashMap<String, Object>> mapList = new ArrayList<>();
        //设置只返回id，减少数据库压力
        List<ReturnCriterion> returnCriterionListList = setReturnFiled(Arrays.asList("id", "table_service", "table_comment", "table_name", "enable_status"));
        //获取返回条件，前端可以根据菜单id查询获取下级菜单，或者根据一级菜单等级获取菜单
        List<WhereCriterion> whereList = new ArrayList<>();
        WhereCriterion upIdWhereCriterion = new WhereCriterion("(", "table_service", ConditionType.等于.getValue(), serverName, "", ConnectType.AND);
        WhereCriterion stsWhereCriterion = new WhereCriterion("", "sts", ConditionType.等于.getValue(), "Y", ")", ConnectType.AND);
        whereList.add(upIdWhereCriterion);
        whereList.add(stsWhereCriterion);
        //查询需要删除的树
        //调用数据查询工具类
        mapList = baseDaoUtilImpl.selectList(tablename, returnCriterionListList, whereList);
        return mapList;
    }

    private List<ReturnCriterion> setReturnFiled(List<String> asList) {
        if (asList != null && asList.size() > 0) {
            List<ReturnCriterion> returnCriterionListList = new ArrayList<>();
            for (int i = 0; i < asList.size(); i++) {
                ReturnCriterion criterion = new ReturnCriterion(asList.get(i));
                returnCriterionListList.add(criterion);
            }
            return returnCriterionListList;
        } else {
            return null;
        }
    }

    /**
     * @param str
     * @return void
     * @Author lvleigang
     * @Description 校验字符串
     * @Date 11:41 上午 2022/12/7
     **/
    private Boolean checkStr(String str) {
        Boolean flag = true;
        if (str == null || "".equals(str)) {
            flag = false;
        }
        return flag;
    }


    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 查询树-配置通用接口
     * 需要传入参数
     * 上级ID字段（可以没有，没有查询字段为 up_id ）
     * 查询条件（可以没有，如果没有默认两个查询条件 lvl 等于0 sts = Y）（注：这个条件只代入第一次查询，后续查询子集仅根据上下级关联关系）
     * 返回字段（可以没有，如果没有返回全部字段  TODO 后续可能会去查询缓存，获取缓存中的返回字段）
     * 排序条件（可以没有，如果没有 默认 sorts 正序）
     * @Date 3:21 下午 2023/2/14
     **/
    @Override
    public JsonResultEntity queryTree(JSONObject jsonObject) {
        //校验数据（只校验表名称）
        if (!checkStr(jsonObject.getString("tableName"))) {
            return BaseResult.getFailureMessageEntity("表名不存在");
        }
        String tablename = jsonObject.getString("tableName");
        JSONObject jsonObject1 = jsonObject.getJSONObject("jsonStr");
        //拼接查询
        //上级字段
        String upID = getStringDataIfNullSetDefault("up_id", "upID", jsonObject1);
        //查询条件
        List<WhereCriterion> whereCriteria = getListDataIfNullSetDefault(defaultWhereCriteria, "wheres", jsonObject1, WhereCriterion.class);
        //返回字段
        List<ReturnCriterion> fileds = getListDataIfNullSetNull("returnCriterions", jsonObject1, ReturnCriterion.class);
        //排序条件
        List<OrderCriterion> order = getListDataIfNullSetDefault(defaultOrder, "order", jsonObject1, OrderCriterion.class);
        //根据条件查询第一级数据
        //查询数据
        List<HashMap<String, Object>> mapList = baseDaoUtilImpl.selectList(tablename, order, fileds, whereCriteria);
        if (mapList != null && mapList.size() > 0) {
            //递归查询子集
            recursiveQueryTree(mapList, tablename, fileds, order, upID);
        }
        //设置返回对象
        return BaseResult.getSuccessMessageEntity("获取树成功", mapList);
    }

    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 删除树-配置通用接口-逻辑删除
     * 需要传入参数
     * 上级ID字段（可以没有，没有查询字段为 up_id ）
     * 查询条件（可以没有，如果没有默认两个查询条件 lvl 等于0 sts = Y）（注：这个条件只代入第一次查询，后续查询子集仅根据上下级关联关系）
     * @Date 3:21 下午 2023/2/14
     **/
    @Override
    public JsonResultEntity delectTree(JSONObject jsonObject) {
        //校验数据（只校验表名称）
        if (!checkStr(jsonObject.getString("tableName"))) {
            return BaseResult.getFailureMessageEntity("表名不存在");
        }
        String tablename = jsonObject.getString("tableName");
        JSONObject jsonObject1 = jsonObject.getJSONObject("jsonStr");
        //拼接查询
        //上级字段
        String upID = getStringDataIfNullSetDefault("up_id", "upID", jsonObject1);
        List<ReturnCriterion> returnCriteria = chectDefaultReturn(upID);
        //查询条件
        List<WhereCriterion> whereCriteria = getListDataIfNullSetDefault(defaultWhereCriteria, "wheres", jsonObject1, WhereCriterion.class);
        //根据条件查询第一级数据
        //查询数据
        List<HashMap<String, Object>> mapList = baseDaoUtilImpl.selectList(tablename, returnCriteria, whereCriteria);
        if (mapList != null && mapList.size() > 0) {
            //递归删除子集
            recursiveDeleteTree(mapList, tablename, upID, returnCriteria);
        }
        //删除当前主节点
        baseDaoUtilImpl.update(tablename, defaultModify, whereCriteria);

        //设置返回对象
        return BaseResult.getSuccessMessageEntity("删除树成功");
    }

    //判断是否是默认
    private List<ReturnCriterion> chectDefaultReturn(String upID) {
        if (upID != null && !"up_id".equals(upID.toLowerCase())) {
            List<ReturnCriterion> returnCriteria = new ArrayList<>();
            returnCriteria.add(new ReturnCriterion("id", "id"));
            returnCriteria.add(new ReturnCriterion(upID, upID));
            return returnCriteria;
        } else {
            return defaultFileds;
        }
    }

    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 查询树节点下级的节点数据
     * 需要传入参数
     * 上级ID字段（可以没有，没有查询字段为 up_id ）
     * 查询条件（必须存在）（注：这个条件只代入第一次查询，后续查询子集仅根据上下级关联关系）
     * 返回字段（可以没有，如果没有返回全部字段  TODO 后续可能会去查询缓存，获取缓存中的返回字段）
     * 排序条件（可以没有，如果没有 默认 sorts 正序）
     * @Date 3:21 下午 2023/2/14
     **/
    @Override
    public JsonResultEntity selectTreeSubordinateList(JSONObject jsonObject) {
        Integer level = 1;
        return selectTreeList(jsonObject, level);
    }

    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 查询树节点下面所有的递归节点数据
     * 需要传入参数
     * 上级ID字段（可以没有，没有查询字段为 up_id ）
     * 查询条件（必须存在）（注：这个条件只代入第一次查询，后续查询子集仅根据上下级关联关系）
     * 返回字段（可以没有，如果没有返回全部字段  TODO 后续可能会去查询缓存，获取缓存中的返回字段）
     * 排序条件（可以没有，如果没有 默认 sorts 正序）
     * @Date 3:21 下午 2023/2/14
     **/
    @Override
    public JsonResultEntity selectTreeAllList(JSONObject jsonObject) {
        Integer level = -1;
        return selectTreeList(jsonObject, level);
    }

    /**
     * @param object
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 查询数据字典
     * @Date 9:25 上午 2023/3/6
     **/
    @Override
    public JsonResultEntity selectDictionaryshop(JSONObject object) {
        //校验数据（只校验表名称）
        String tablename = "sys_dictionaryshop_new";
        JSONObject jsonObject = object.getJSONObject("jsonStr");
        List<WhereCriterion> whereCriteria = new ArrayList<>();
        whereCriteria.add(new WhereCriterion("(", "sts", ConditionType.等于.getValue(), "Y", ")", ConnectType.AND));
        whereCriteria.add(new WhereCriterion("(", "used_sts", ConditionType.等于.getValue(), "1", ")", ConnectType.AND));
        if (jsonObject != null) {
            String tabName = getStringDataIfNullSetDefault(null, "tab_name", jsonObject);
            if (tabName != null && !"".equals(tabName)) {
                whereCriteria.add(new WhereCriterion("(", "tab_name", ConditionType.等于.getValue(), tabName, ")", ConnectType.AND));
            }
            String columnName = getStringDataIfNullSetDefault(null, "column_name", jsonObject);
            if (columnName != null && !"".equals(columnName)) {
                whereCriteria.add(new WhereCriterion("(", "column_name", ConditionType.等于.getValue(), columnName, ")", ConnectType.AND));
            }
        }
        List<HashMap<String, Object>> list = null;
        try {
            list = baseDaoUtilImpl.selectWhereList(tablename, defaultOrder, whereCriteria);
            return BaseResult.getSuccessMessageEntity("查询成功", list);
        } catch (Exception e) {
            log.error("default：selectList{}", e.getMessage());
            return BaseResult.getFailureMessageEntity("查询失败");
        }
    }

    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 查询树节点下面的递归节点数据
     * 需要传入参数
     * 上级ID字段（可以没有，没有查询字段为 up_id ）
     * 查询条件（必须存在）（注：这个条件只查当前级别，可以是id 可也以是别的限定条件，查询数据库只能查出一条否则返回错误）
     * 返回字段（可以没有，如果没有返回全部字段  TODO 后续可能会去查询缓存，获取缓存中的返回字段）
     * 排序条件（可以没有，如果没有 默认 sorts 正序）
     * 分页信息（可以没有，如果没有 默认 第一页 10条 ）
     * @Date 3:21 下午 2023/2/14
     **/
    private JsonResultEntity selectTreeList(JSONObject jsonObject, Integer level) {
        //校验数据（只校验表名称）
        if (!checkStr(jsonObject.getString("tableName"))) {
            return BaseResult.getFailureMessageEntity("表名不存在");
        }
        String tablename = jsonObject.getString("tableName");
        JSONObject jsonObject1 = jsonObject.getJSONObject("jsonStr");
        //拼接查询
        //上级字段
        String upID = getStringDataIfNullSetDefault("up_id", "upID", jsonObject1);
        List<ReturnCriterion> returnCriteria = chectDefaultReturn(upID);

        //查询条件
        List<WhereCriterion> nodeWheres = getListDataIfNullSetNull("nodeWheres", jsonObject1, WhereCriterion.class);
        if (nodeWheres == null && nodeWheres.size() == 0) {
            return BaseResult.getFailureMessageEntity("查询条件不存在");
        }
        List<WhereCriterion> whereCriteria = getListDataIfNullSetNull("wheres", jsonObject1, WhereCriterion.class);
        //返回字段
        List<ReturnCriterion> fileds = getListDataIfNullSetNull("returnCriterions", jsonObject1, ReturnCriterion.class);
        //排序条件
        List<OrderCriterion> order = getListDataIfNullSetDefault(defaultOrder, "order", jsonObject1, OrderCriterion.class);

        Integer pageNum = getIntegerDataIfNullSetDefault(1, "pageNum", jsonObject1);
        Integer pageSize = getIntegerDataIfNullSetDefault(10, "pageSize", jsonObject1);

        //根据条件查询第一级数据
        //查询数据
        List<HashMap<String, Object>> mapList = baseDaoUtilImpl.selectList(tablename, returnCriteria, nodeWheres);
        List<String> ids = null;
        if (mapList != null && mapList.size() == 1) {
            //递归查询子集
            ids = recursiveQueryTreeListId(mapList, tablename, returnCriteria, upID, level);
        } else {
            return BaseResult.getFailureMessageEntity("查询当前节点错误");
        }
        if (ids != null && ids.size() > 0) {
            whereCriteria = whereCriteria == null ? new ArrayList<WhereCriterion>() : whereCriteria;
            whereCriteria.add(new WhereCriterion("(", "id", ConditionType.在列表.getValue(), ids, ")", ConnectType.AND));
            PageInfo pageInfo = baseDaoUtilImpl.selectPage(tablename, order, fileds, whereCriteria, pageNum, pageSize);
            //设置返回对象
            return BaseResult.getSuccessMessageEntity("获取树列表成功", pageInfo);
        } else {
            //设置一个空的分页对象返回
            return BaseResult.getSuccessMessageEntity("获取树列表成功", new PageInfo());
        }
    }

    /**
     * @param mapList       上级数据
     * @param tablename     表名
     * @param defaultFileds 查询字段
     * @param upID          上级id字段
     * @param level         查询级别
     * @return java.util.List<java.lang.String>
     * @Author lvleigang
     * @Description 递归查询下级所有的id
     * @Date 4:59 下午 2023/2/16
     **/
    private List<String> recursiveQueryTreeListId(List<HashMap<String, Object>> mapList, String tablename, List<ReturnCriterion> defaultFileds, String upID, Integer level) {
        //判断是否有数据
        List<String> ids = new ArrayList<>();
        if (level != 0) {
            if (mapList != null && mapList.size() > 0) {
                for (int i = 0; i < mapList.size(); i++) {
                    //设置条件，此处递归查询只要设置上级id和状态就行
                    List<WhereCriterion> whereList = new ArrayList<>();
                    WhereCriterion upIdWhereCriterion = new WhereCriterion("(", upID, ConditionType.等于.getValue(), mapList.get(i).get("id"), "", ConnectType.AND);
                    WhereCriterion stsWhereCriterion = new WhereCriterion("", "sts", ConditionType.等于.getValue(), "Y", ")", ConnectType.AND);
                    whereList.add(upIdWhereCriterion);
                    whereList.add(stsWhereCriterion);
                    //查询数据
                    List<HashMap<String, Object>> childList = baseDaoUtilImpl.selectList(tablename, defaultFileds, whereList);
                    if (childList != null && childList.size() > 0) {
                        //递归调用
                        ids.addAll(recursiveQueryTreeListId(childList, tablename, defaultFileds, upID, --level));
                        //设置下级菜单
                        childList.stream().forEach(s -> ids.add((String) s.get("id")));
                    }
                }
            }
        }
        return ids;
    }

    private Integer getIntegerDataIfNullSetDefault(Integer defaultValue, String key, JSONObject jsonObject) {
        if (checkInt(jsonObject.getInteger(key))) {
            return jsonObject.getInteger(key);
        }
        return defaultValue;
    }

    private boolean checkInt(Integer integer) {
        Boolean flag = true;
        if (integer == null) {
            flag = false;
        }
        return flag;
    }

    /**
     * @param mapList   数据
     * @param tablename 表明
     * @param upID      上级id字段
     * @return void
     * @Author lvleigang
     * @Description 递归查询删除数据
     * @Date 2:33 下午 2023/2/15
     **/
    private void recursiveDeleteTree(List<HashMap<String, Object>> mapList, String tablename, String upID, List<ReturnCriterion> returnCriteria) {
        //判断是否有数据
        if (mapList != null && mapList.size() > 0) {
            for (int i = 0; i < mapList.size(); i++) {
                //设置条件，此处递归查询只要设置上级id和状态就行
                List<WhereCriterion> whereList = new ArrayList<>();
                WhereCriterion upIdWhereCriterion = new WhereCriterion("(", upID, ConditionType.等于.getValue(), mapList.get(i).get("id"), "", ConnectType.AND);
                WhereCriterion stsWhereCriterion = new WhereCriterion("", "sts", ConditionType.等于.getValue(), "Y", ")", ConnectType.AND);
                whereList.add(upIdWhereCriterion);
                whereList.add(stsWhereCriterion);
                //查询数据
                List<HashMap<String, Object>> childList = baseDaoUtilImpl.selectList(tablename, returnCriteria, whereList);
                if (childList != null && childList.size() > 0) {
                    //递归调用
                    recursiveDeleteTree(childList, tablename, upID, returnCriteria);
                }
                //删除当前节点
                baseDaoUtilImpl.update(tablename, defaultModify, whereList);
            }
        }
    }

    /**
     * @param mapList
     * @param tablename
     * @param fileds
     * @param order
     * @param upID
     * @return void
     * @Author lvleigang
     * @Description 递归查询子集
     * @Date 4:47 下午 2023/2/14
     **/
    private void recursiveQueryTree(List<HashMap<String, Object>> mapList, String tablename, List<ReturnCriterion> fileds, List<OrderCriterion> order, String upID) {
        //判断是否有数据
        if (mapList != null && mapList.size() > 0) {
            for (int i = 0; i < mapList.size(); i++) {
                //设置条件，此处递归查询只要设置上级id和状态就行
                List<WhereCriterion> whereList = new ArrayList<>();
                WhereCriterion upIdWhereCriterion = new WhereCriterion("(", upID, ConditionType.等于.getValue(), mapList.get(i).get("id"), "", ConnectType.AND);
                WhereCriterion stsWhereCriterion = new WhereCriterion("", "sts", ConditionType.等于.getValue(), "Y", ")", ConnectType.AND);
                whereList.add(upIdWhereCriterion);
                whereList.add(stsWhereCriterion);
                //查询数据
                List<HashMap<String, Object>> childList = baseDaoUtilImpl.selectList(tablename, order, fileds, whereList);
                if (childList != null && childList.size() > 0) {
                    //递归调用
                    recursiveQueryTree(childList, tablename, fileds, order, upID);
                    //设置下级菜单
                    mapList.get(i).put("childMenu", childList);
                }
            }
        }
    }

    /**
     * @param key        健
     * @param jsonObject json数据
     * @return java.lang.String
     * @Author lvleigang
     * @Description 根据key获取数据jsonObject中的数据，如果没有返回null
     * @Date 3:41 下午 2023/2/14
     **/
    private <T> List<T> getListDataIfNullSetNull(String key, JSONObject jsonObject, Class<T> clz) {
        return getListDataIfNullSetDefault(null, key, jsonObject, clz);
    }

    /**
     * @param defaultList 默认值
     * @param key         健
     * @param jsonObject  json数据
     * @return java.lang.String
     * @Author lvleigang
     * @Description 根据key获取数据jsonObject中的数据，如果没有设置默认值
     * @Date 3:41 下午 2023/2/14
     **/
    private <T> List<T> getListDataIfNullSetDefault(List<T> defaultList, String key, JSONObject jsonObject, Class<T> clz) {
        //checkList 方法可能有漏洞，需要后续测试
        if (checkStr(jsonObject.getString(key)) && checkList(jsonObject.getJSONArray(key))) {
            JSONArray jsonArray = jsonObject.getJSONArray(key);
            return jsonArray.toJavaList(clz);
        }
        return defaultList;
    }

    /**
     * @param jsonArray
     * @return boolean
     * @Author lvleigang
     * @Description 校验数据是否为空
     * @Date 4:18 下午 2023/2/14
     **/
    private boolean checkList(JSONArray jsonArray) {
        Boolean flag = true;
        if (jsonArray == null || jsonArray.size() == 0) {
            flag = false;
        }
        return flag;
    }

    /**
     * @param defaultValue 默认值
     * @param key          健
     * @param jsonObject   json数据
     * @return java.lang.String
     * @Author lvleigang
     * @Description 根据key获取数据jsonObject中的数据，如果没有设置默认值
     * @Date 3:41 下午 2023/2/14
     **/
    private String getStringDataIfNullSetDefault(String defaultValue, String key, JSONObject jsonObject) {
        if (checkStr(jsonObject.getString(key))) {
            return jsonObject.getString(key);
        }
        return defaultValue;
    }
}
