package cn.com.capcloud.api.action.service;

import cn.com.capcloud.api.KHCResponseEntity;
import cn.com.capcloud.ccui.core.common.json.JackJSON;
import cn.com.capcloud.ccui.core.common.json.JackJSONArray;
import cn.com.capcloud.ccui.core.common.json.JackJSONObject;
import cn.com.capcloud.core.noentitydb.DBCheck;
import cn.com.capcloud.core.util.*;
import com.deepoove.poi.XWPFTemplate;
import cn.com.capcloud.core.cache.KHCRedisCache;
import cn.com.capcloud.core.cache.BaseConfigStaticCache;
import cn.com.capcloud.core.execl.xls.CellForm;
import cn.com.capcloud.core.execl.xls.CellFormat;
import cn.com.capcloud.core.execl.xls.ExeclFileObject;
import cn.com.capcloud.core.execl.xlsx.ExcelOneUtil;
import cn.com.capcloud.core.execl.xlsx.ExcelUtil;
import cn.com.capcloud.core.noentitydb.BaseDao;
import cn.com.capcloud.core.noentitydb.BaseService;
import cn.com.capcloud.core.noentitydb.JtPage;
import cn.com.capcloud.core.system.user.User;
import cn.com.capcloud.core.system.user.UserService;
import cn.com.capcloud.core.websocket.RedisPublication;
import com.deepoove.poi.config.Configure;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import org.joda.time.DateTime;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Method;
import java.util.*;

@Service
public class ApiService {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ApiService.class);

    //PDF默认模板
    private static final String SYSTEM_SETTINGS_DS_FORM_PDF_TEMPLATE="system.settings.ds.form.pdf.template";
    @Resource
    private UserService userService;
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private MongoService mongoService;
    @Resource
    private MinioService minioService;
    @Resource
    private ReadProperty readProperty;
    @Resource
    private BaseService baseService;
    @Resource
    private KHCRedisCache khcRedisCache;
    @Resource
    private RedisPublication redisPublication;

    public String getDataSourceUuid(String jsonStr, JackJSONObject retJson, JackJSONObject dataJson) {
        String dsCode=getJsonValueByKey(jsonStr,retJson,"dsCode");
        if("-1".equals(dsCode)){
            return "-1";
        }else{
            Map<String,Object> map=findDataSourceByCode(dsCode);
            if(map==null){
                retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("7040")));
                retJson.put("message",retJson.get("message")+" dsCode："+dsCode);
                return "-1";
            }else{
                return String.valueOf(map.get("uuid"));
            }
        }
    }
    //附件上传使用
    public String getDataSourceUuid(JackJSONObject retJson, HttpServletRequest request) {
        String dsCode=getRequestValueByKey(request,retJson,"dsCode");
        if("-1".equals(dsCode)){
            return "-1";
        }else{
            Map<String,Object> map=findDataSourceByCode(dsCode);
            if(map==null){
                retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("7040")));
                retJson.put("message",retJson.get("message")+" dsCode："+dsCode);
                return "-1";
            }else{
                return String.valueOf(map.get("uuid"));
            }
        }
    }
    public Map<String,Object> executeMyActionMethod(String jsonStr, JackJSONObject retJson, HttpServletRequest request) {
        String dsCode=getJsonValueByKey(jsonStr,retJson,"dsCode");
        Map<String,Object> map=findDataSourceByCode(dsCode);
        String className=String.valueOf(map.get("my_action_class"));
        if("null".equals(className)||className.length()==0){
            retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("6010")));
            retJson.put("message",retJson.get("message")+" dsCode："+dsCode);
            return new HashMap<>();
        }else{
            String methodName=getJsonValueByKey(jsonStr,retJson,"methodName");
            if("-1".equals(methodName)){
                return new HashMap<>();
            }else{
                if(ApiDao.isMethod(className,methodName)){
                    return ApiDao.mySelfMethodRetMap(className,methodName,jsonStr,retJson,request);
                }else{
                    retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("6010")));
                    retJson.put("message",retJson.get("message")+" methodName："+methodName+"()");
                    return new HashMap<>();
                }
            }
        }
    }
    public String getDataSourceUuid(String jsonStr) {//内部使用
        JackJSONObject jsonObject = JackJSONObject.fromObject(jsonStr);
        String dsCode=String.valueOf(jsonObject.get("dsCode"));
        Map<String,Object> map=findDataSourceByCode(dsCode);
        return String.valueOf(map.get("uuid"));
    }
    public String getJsonValueByKey(String jsonStr, JackJSONObject retJson, String key) {
        JackJSONObject jsonObject = JackJSONObject.fromObject(jsonStr);
        String value=String.valueOf(jsonObject.get(key));
        if("null".equals(value)||value.length()==0){
            retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("7010")));
            retJson.put("message",retJson.get("message")+"："+key);
            return "-1";
        }else{
            return value;
        }
    }
    public String getRequestValueByKey(HttpServletRequest request, JackJSONObject retJson,String key) {
        String data=request.getParameter("data");
        if(data!=null){
            JackJSONObject jsonObject = JackJSONObject.fromObject(data);
            String value=String.valueOf(jsonObject.get(key));
            if("null".equals(value)||value.length()==0){
                retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("7010")));
                retJson.put("message",retJson.get("message")+"："+key);
                return "-1";
            }else{
                return value;
            }
        }else{
            retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("7010")));
            retJson.put("message",retJson.get("message")+"："+key);
            return "-1";
        }
    }

    public String getDataSourceInfo(String jsonStr, String uuid, JackJSONObject retJson, JackJSONObject dataJson) {
        JackJSONObject dsJson=new JackJSONObject();
        dsJson.put("ds_pk_id",findDataSourceByUuid(uuid).get("ds_pk_id"));
        dataJson.put("ds",dsJson);
        return "0";
    }

    public String getFormInfo(String jsonStr, String uuid, JackJSONObject retJson, JackJSONObject dataJson,HttpServletRequest request) {
        JackJSONObject jsonObject = JackJSONObject.fromObject(jsonStr);
        JackJSONObject formJson = new JackJSONObject();
        String formCode=String.valueOf(jsonObject.get("formCode"));
        if("null".equals(formCode)||formCode.length()==0){
            return "0";//formCode允许为空 继续往下执行
        }else{
            Map<String, Object> formMap=getForm(uuid,formCode);
            if(formMap.size()==0){
                retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("7040")));
                retJson.put("message",retJson.get("message")+"formCode："+formCode);
                return "-1";
            }else{
                String formUuid=String.valueOf(formMap.get("uuid"));
                String formVersion=String.valueOf(jsonObject.get("formVersion"));
                if("null".equals(formVersion)||formVersion.length()==0){// 入参没有传此参数则取出表单组件绑定的。
                    formVersion=String.valueOf(formMap.get("form_version"));
                }
                //clearValue说明：关于是使用默认的clearValue还是使用自定义四的clearValue（自定义的则需要先绑定扩展js，然后再扩展js里写clearValue函数即可）
                List<Map<String, Object>> dataList;
                if(!"null".equals(formVersion)&&formVersion.length()>0){
                    dataList = khcRedisCache.getFormInfoByUuidAndVersion(formUuid,formVersion);
                }else{
                    dataList = khcRedisCache.getFormInfoByUuid(formUuid);
                }
                List<Map<String, Object>> formData = new ArrayList<>();
                User user=userService.getUser(request);
                for (int i = 0; i < dataList.size(); i++) {
                    Map<String,Object> map= new HashMap<>();
                    Map<String,Object> dataMap= dataList.get(i);
                    Object dictCode = dataMap.get("dict_code");
                    String code;
                    if (dictCode instanceof HashMap) {
                        code=String.valueOf(((HashMap<?, ?>) dictCode).get("code"));
                    }else{
                        code=String.valueOf(dataMap.get("dict_code"));
                    }
                    if(!"null".equals(code)&&code.length()>0){
                        dataMap.put("dict_code",getAllDictInfoByCode(code,user));
                    }
                    map.put("data",dataMap);
                    map.put("name",dataList.get(i).get("name"));
                    map.put("show_type",dataList.get(i).get("show_type"));
                    formData.add(map);
                }
                //查询按钮
                formJson.put("formInfo",formMap);
                formJson.put("formButton",getButtonFilter(khcRedisCache.getButtonByParentUUID(String.valueOf(formMap.get("uuid")),""),request));
                formJson.put("formData",formData);
                dataJson.put("form",formJson);
                return "0";
            }
        }
    }
    public List<Map<String, Object>> getFormInfo(String jsonStr) {//内部使用
        JackJSONObject jsonObject = JackJSONObject.fromObject(jsonStr);
        String uuid=getDataSourceUuid(jsonStr);
        String formCode=String.valueOf(jsonObject.get("formCode"));
        Map<String, Object> map=getForm(uuid,formCode);
        String pageParentUuid=String.valueOf(map.get("uuid"));
        String sql="SELECT * FROM tbl_data_form_info WHERE STATUS=0 AND page_parent_uuid='"+pageParentUuid+"' ORDER BY field_sort ASC ";
        List<Map<String, Object>> dataList = jdbcTemplate.queryForList(sql);
        return dataList;
    }
    public List<Map<String, Object>> getFormInfoByUuid(String pageParentUuid) {//内部使用
        String sql="SELECT * FROM tbl_data_form_info WHERE STATUS=0 AND page_parent_uuid='"+pageParentUuid+"' ORDER BY field_sort ASC ";
        List<Map<String, Object>> dataList = jdbcTemplate.queryForList(sql);
        return dataList;
    }
    public String getQueryInfo(String jsonStr, String uuid, JackJSONObject retJson, JackJSONObject dataJson, HttpServletRequest request) {
        JackJSONObject jsonObject = JackJSONObject.fromObject(jsonStr);
        JackJSONObject queryJson = new JackJSONObject();
        String queryCode=String.valueOf(jsonObject.get("queryCode"));
        if("null".equals(queryCode)||queryCode.length()==0){
            return "0";//formCode允许为空 继续
        }else{
            Map<String, Object> queryMap=getQuery(uuid,queryCode);
            if(queryMap.size()==0){
                retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("7040")));
                retJson.put("message",retJson.get("message")+"queryCode："+queryCode);
                return "-1";
            }else{
                String queryUuid=String.valueOf(queryMap.get("uuid"));
                List<Map<String, Object>> dataList = khcRedisCache.getQueryInfoByUuid(queryUuid);
                List<Map<String, Object>> queryData = new ArrayList<>();
                User user=userService.getUser(request);
                for (int i = 0; i < dataList.size(); i++) {
                    Map<String,Object> map= new HashMap<>();
                    Map<String,Object> dataMap= dataList.get(i);
                    Object dictCode = dataMap.get("dict_code");
                    String code;
                    if (dictCode instanceof HashMap) {
                        code=String.valueOf(((HashMap<?, ?>) dictCode).get("code"));
                    }else{
                        code=String.valueOf(dataMap.get("dict_code"));
                    }
                    if(!"null".equals(code)&&code.length()>0){
                        dataMap.put("dict_code",getAllDictInfoByCode(code,user));
                    }
                    map.put("data",dataMap);
                    map.put("name",dataList.get(i).get("name"));
                    map.put("show_type",dataList.get(i).get("show_type"));
                    queryData.add(map);
                }
                //查询按钮
                queryMap.put("rowButtonArray", getButtonFilter(khcRedisCache.getButtonByParentUUID(String.valueOf(queryMap.get("uuid"))," and button_type='rowButton'"),request));
                queryMap.put("tableButtonArray", getButtonFilter(khcRedisCache.getButtonByParentUUID(String.valueOf(queryMap.get("uuid"))," and button_type='tableButton'"),request));
                queryMap.put("queryButtonArray", getButtonFilter(khcRedisCache.getButtonByParentUUID(String.valueOf(queryMap.get("uuid"))," and button_type='queryButton'"),request));
                String sql="select * from tbl_data_query_simple_card where status=0 and simple_caard_status=0 and page_parent_uuid='"+queryMap.get("uuid")+"'";
                queryMap.put("querySimpleCardArray", JackJSON.parseObject(ApiDao.nullToStrFilter(jdbcTemplate.queryForList(sql)), ArrayList.class));
                queryJson.put("queryInfo",queryMap);
                queryJson.put("queryData",queryData);
                dataJson.put("query",queryJson);
                return "0";
            }
        }
    }
    //如果没有按钮角色权限则过滤掉。
    public List<Map<String, Object>> getButtonFilter(List<Map<String, Object>> buttons,HttpServletRequest request){
        List<Map<String, Object>> filterButtons=new ArrayList<>();
        if(buttons.size()>0){
            User user=userService.getUser(request);
            for (int i = 0; i < buttons.size(); i++) {
                String roleStr=String.valueOf(buttons.get(i).get("button_role"));
                if(roleStr.equals("")){//空则不控制按钮权限
                    filterButtons.add(buttons.get(i));
                }else{
                    String[] roleArr=roleStr.split(",");
                    for (int j = 0; j < roleArr.length; j++) {
                        if(userService.isExistsRole(roleArr[j], user.getId())) {
                            filterButtons.add(buttons.get(i));
                            break;
                        }
                    }
                }
            }
        }
        return filterButtons;
    }
    public List<Map<String, Object>> getQueryInfo(String jsonStr) {//内部使用
        JackJSONObject jsonObject = JackJSONObject.fromObject(jsonStr);
        String uuid=getDataSourceUuid(jsonStr);
        String queryCode=String.valueOf(jsonObject.get("queryCode"));
        Map<String, Object> map=getQuery(uuid,queryCode);
        String pageParentUuid=String.valueOf(map.get("uuid"));
        String sql="SELECT * FROM tbl_data_query_info WHERE STATUS=0 AND page_parent_uuid='"+pageParentUuid+"' ORDER BY field_sort ASC ";
        List<Map<String, Object>> dataList = jdbcTemplate.queryForList(sql);
        return dataList;
    }
    public Map<String, Object> getForm(String jsonStr) {
        JackJSONObject jsonObject = JackJSONObject.fromObject(jsonStr);
        String uuid=getDataSourceUuid(jsonStr);
        String formCode=String.valueOf(jsonObject.get("formCode"));
        Map<String, Object> map=getForm(uuid,formCode);
        return map;
    }
    public Map<String, Object> getForm(String uuid,String code) {
        String sql="SELECT * FROM tbl_data_form WHERE STATUS=0 AND page_parent_uuid='"+uuid+"' AND form_code='"+code+"'";
        List<Map<String, Object>> list=jdbcTemplate.queryForList(sql);
        if(list.size()>0){
            return list.get(0);
        }else{
            return new HashMap<>();
        }
    }
    public Map<String, Object> getForm(String uuid,String code,JackJSONObject retJson) {
        String sql="SELECT * FROM tbl_data_form WHERE STATUS=0 AND page_parent_uuid='"+uuid+"' AND form_code='"+code+"'";
        List<Map<String, Object>> list=jdbcTemplate.queryForList(sql);
        if(list.size()>0){
            return list.get(0);
        }else{
            retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("7040")));
            retJson.put("message",retJson.get("message")+"formCode："+code);
            return new HashMap<>();
        }
    }
    public Map<String, Object> getQuery(String jsonStr) {
        JackJSONObject jsonObject = JackJSONObject.fromObject(jsonStr);
        String uuid=getDataSourceUuid(jsonStr);
        String queryCode=String.valueOf(jsonObject.get("queryCode"));
        Map<String, Object> map=getQuery(uuid,queryCode);
        return map;
    }
    public Map<String, Object> getQuery(String uuid,String code) {
        String sql="SELECT * FROM tbl_data_query WHERE STATUS=0 AND page_parent_uuid='"+uuid+"' AND query_code='"+code+"'";
        List<Map<String, Object>> list=jdbcTemplate.queryForList(sql);
        if(list.size()>0){
            return list.get(0);
        }else{
            return new HashMap<>();
        }
    }
    public Map<String, Object> getQuery(String uuid,String code,JackJSONObject retJson) {
        String sql="SELECT * FROM tbl_data_query WHERE STATUS=0 AND page_parent_uuid='"+uuid+"' AND query_code='"+code+"'";
        List<Map<String, Object>> list=jdbcTemplate.queryForList(sql);
        if(list.size()>0){
            return list.get(0);
        }else{
            retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("7040")));
            retJson.put("message",retJson.get("message")+"queryCode："+code);
            return new HashMap<>();
        }
    }
    public String getQuery(String jsonStr, String uuid, JackJSONObject retJson, JackJSONObject dataJson) {
        JackJSONObject jsonObject = JackJSONObject.fromObject(jsonStr);
        String queryCode=String.valueOf(jsonObject.get("queryCode"));
        if("null".equals(queryCode)||queryCode.length()==0){
            return "0";//formCode允许为空 继续
        }else{
            Map<String, Object> map=getQuery(uuid,queryCode);
            if(map.size()==0){
                retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("7040")));
                retJson.put("message",retJson.get("message")+"queryCode："+queryCode);
                return "-1";
            }else{
                return "0";
            }
        }
    }

    public void setContentType(HttpServletResponse response,String suffix) {
        if (suffix.toLowerCase().equals("png")) {
            response.setContentType("image/png");
        }
        if (suffix.toLowerCase().equals("bmp")) {
            response.setContentType("image/bmp");
        }
        if (suffix.toLowerCase().equals("gif")) {
            response.setContentType("image/gif");
        }
        if (suffix.toLowerCase().equals("jpeg")) {
            response.setContentType("image/jpeg");
        }
        if (suffix.toLowerCase().equals("tiff")) {
            response.setContentType("image/tiff");
        }
        if (suffix.toLowerCase().equals("txt")) {
            response.setContentType("text/plain");
        }
        if (suffix.toLowerCase().equals("pdf")) {
            response.setContentType("application/pdf");
        }
        if (suffix.toLowerCase().equals("doc")) {
            response.setContentType("application/msword");
        }
        if (suffix.toLowerCase().equals("docx")) {
            response.setContentType("application/msword");
        }
        if (suffix.toLowerCase().equals("xls")) {
            response.setContentType("application/vnd.ms-excel");
        }
        if (suffix.toLowerCase().equals("xlsx")) {
            response.setContentType("application/vnd.ms-excel");
        }
    }
    /**
     * 加密字符串
     */
    public String smEncrypt(String str) {
        return ApiDao.smDecrypt(str,readProperty.getSmPubKey());
    }
    /**
     * 解密字符串
     */
    public String smDecrypt(String str) {
        return ApiDao.smDecrypt(str,readProperty.getSmPriKey());
    }
    /**
     * 查询内部字典
     */
    public List<Map<String, Object>> getDictInfoByDictCodeToList(String dictCode) {
        return ApiDao.getDictInfoByDictCodeToList(dictCode,jdbcTemplate);
    }
    public Map<String, Object> getDictInfoByDictCodeToMap(String dictCode,Boolean isReversal) {
        return ApiDao.getDictInfoByDictCodeToMap(dictCode,isReversal,jdbcTemplate);
    }
    /**
     * 查询外部字典
     */
    public Map<String, Object> getOutDictInfoByDictCodeToMap(String dictCode,Boolean isReversal) {
        return ApiDao.getOutDictInfoByDictCodeToMap(dictCode,isReversal,jdbcTemplate);
    }
    /**
     * 根据前缀来判断查询内部字典还是外部字典
     */
    public Map<String, Object> getAllDictInfoByCode(String code, User user) {
        Map<String, Object> retMap=new HashMap<>();
        retMap.put("code", code);
        String userId="";
        if(user!=null){
            userId=String.valueOf(user.getId());
        }
        if(code.indexOf("tree_")==0){
            retMap.put("type", "tree");
            retMap.put("data", khcRedisCache.getTreeInfoByTreeCodeToList(code,"",userId,user));
        }else if(code.indexOf("o_")==0){//外部字典不放缓存。
            retMap.put("type", "default");
            retMap.put("data", ApiDao.getOutDictInfoByDictCodeToList(code,jdbcTemplate,user));
        }else if(code.indexOf("tp_")==0){//第三方字典不放缓存。
            retMap.put("type", "default");
            retMap.put("data", ApiDao.getTPDictInfoByDictCodeToList(code,jdbcTemplate));
        }else{
            retMap.put("type", "default");
            retMap.put("data", khcRedisCache.getDictInfoByDictCodeToList(code));
        }
        return retMap;
    }
    public Map<String, Object> getAllDictInfoByCode(String code) {
        return getAllDictInfoByCode(code,null);
    }
    public Map<String, Object> findDataSourceByUuid(String uuid) {
        return ApiDao.findDataSource(uuid,null,jdbcTemplate);
    }
    public Map<String, Object> findDataSourceByCode(String dsCode) {
        return ApiDao.findDataSource(null,dsCode,jdbcTemplate);
    }
    public Map<String, Object> findDataSourceByJsonStr(String jsonStr) {
        JackJSONObject jsonObject = JackJSONObject.fromObject(jsonStr);
        String dsCode=String.valueOf(jsonObject.get("dsCode"));
        Map<String,Object> map=findDataSourceByCode(dsCode);
        return map;
    }
    public Map<String, Object> getReturnDataByCode(String code) {
        return ApiDao.getReturnDataByCode(code,jdbcTemplate);
    }

    /**
     *
     * @param cudType 操作类型
     * @param ids 操作对象id
     * @param dsMap 数据源Map
     * @param request
     * @param newSaveData 保存或修改后的数据对象
     * @param oldSaveData 修改前的数据对象
     */
    public void cudLogSave(String cudType, String ids, Map<String, Object> dsMap, HttpServletRequest request, JackJSONArray newSaveData, JackJSONArray oldSaveData) {
        User user=userService.getUser(request);
        Map<String, Object> map=new HashMap<>();
        BaseDao.setDefaultValue(map,user);
        map.put("ds_code",dsMap.get("ds_code"));
        map.put("ds_table_name",dsMap.get("ds_table_name"));
        map.put("type",cudType);
        map.put("data",ids);
        if(cudType.equals("create")&&newSaveData.size()==1){
            map.put("new_data",newSaveData.getJackJSONObject(0).toString());
        }
        if(cudType.equals("update")&&newSaveData.size()==1){
            map.put("new_data",newSaveData.getJackJSONObject(0).toString());
            map.put("old_data",oldSaveData.getJackJSONObject(0).toString());
        }
        if(cudType.equals("delete")&&oldSaveData.size()==1){
            map.put("old_data",oldSaveData.getJackJSONObject(0).toString());
        }
        if(DBCheck.isMongoDB()){
            mongoService.save("tbl_data_cud_log",map);
        }else{
            baseService.save("tbl_data_cud_log",map);
        }
    }
    public void fileLogSave(Map<String, Object> data, HttpServletRequest request) {
        Map<String,Object> fileInfo= (Map<String, Object>) data.get("fileInfo");
        User user=userService.getUser(request);
        Map<String, Object> map=new HashMap<>();
        BaseDao.setDefaultValue(map,user);
        map.put("upload_file_to_type",fileInfo.get("source"));
        map.put("real_file_name",fileInfo.get("realFileName"));
        map.put("suffix",fileInfo.get("suffix"));
        map.put("disk_file_name",fileInfo.get("diskFileName"));
        map.put("file_size",fileInfo.get("fileSize"));
        map.put("file_show_size",fileInfo.get("fileShowSize"));
        List<Map<String,Object>> fileList=new ArrayList<>();
        fileList.add(fileInfo);
        map.put("file", JackJSON.toJSONString(fileList));
        if(DBCheck.isMongoDB()){
            mongoService.save("tbl_data_file_log",map);
        }else{
            baseService.save("tbl_data_file_log",map);
        }
    }
    public void apiLogSave(String  jsonStr, HttpServletRequest request, KHCResponseEntity khcResponseEntity,long startTime) {
        JackJSONObject jsonObject=JackJSONObject.fromObject(jsonStr);
        String apiPath = request.getRequestURI().replace(request.getContextPath(), "");
        // 不需要存储日志的方法
        Set<String> validLogSaveMethodName = new HashSet<>(Arrays.asList("getSystemNotifyList", "getMenu","getSimpleCardInfo"));
        if(apiPath.equals("/api/data/myAction")&&validLogSaveMethodName.contains(String.valueOf(jsonObject.get("methodName")))){
            return;
        }
        User user=userService.getUser(request);
        Map<String, Object> map=new HashMap<>();
        if(apiPath.equals("/api/data/myAction")){
            map.put("api_log_method_name",jsonObject.get("methodName"));
        }else{
            // 获取最后一部分
            String methodName = apiPath.substring(apiPath.lastIndexOf("/") + 1);
            map.put("api_log_method_name",methodName);
        }
        BaseDao.setDefaultValue(map,user);
        map.put("api_action_code",jsonObject.get("dsCode"));
        map.put("api_action_name",jsonObject.get("dsCode"));
        map.put("api_log_url",apiPath);
        map.put("api_log_request_json",jsonStr);
        map.put("api_log_response_json",JackJSON.toJSONString(khcResponseEntity));
        map.put("api_log_response_status",khcResponseEntity.getStatus());
        map.put("api_log_response_uuid",khcResponseEntity.getUuid());//String method = request.getMethod();
        map.put("api_log_usage_time",System.currentTimeMillis() - startTime);
        String ip= IPUtil.getIpAddress(request);
        map.put("ip",ip);
        if(DBCheck.isMongoDB()){
            mongoService.save("tbl_data_api_log",map);
        }else{
            baseService.save("tbl_data_api_log",map);
        }
    }

    /**
     * 目前有两个验证
     * 1，表单配置is_unique=Y 验证数据是否唯一
     * 2，验证值的长度是否超过最大长度，超过则返回相应提示信息
     */
    public String saveBeforeValidate(String  jsonStr,JackJSONArray saveDataArray,JackJSONObject retJson,HttpServletRequest request) {
        Map<String,Object> dsMap=findDataSourceByJsonStr(jsonStr);
        String tableName=String.valueOf(dsMap.get("ds_table_name"));
        List<Map<String,Object>> mapList= BaseDao.getAllCommentsByTableName(tableName, jdbcTemplate);
        Map<String,String> typeMap=new HashMap<String,String>();
        Map<String,Integer> widthMap=new HashMap<String,Integer>();
        List<Object> valueList=new ArrayList<Object>();
        String filedName="Field";
        String fieldType="Type";
        if(DBCheck.isKingbase()){
            filedName="column_name";
            fieldType="data_type";
        }
        for(int k=0;k<mapList.size();k++) {
            Map<String,Object> field=mapList.get(k);
            typeMap.put(String.valueOf(field.get(filedName)), String.valueOf(field.get(fieldType)));
            valueList.add(field.get(filedName));

            if(DBCheck.isKingbase()){
                if(field.get(fieldType).equals("varchar")) {
                    String width=field.get("character_maximum_length").toString();
                    widthMap.put(String.valueOf(field.get(filedName)), Integer.parseInt(width));
                }
            }else{
                if(field.get(fieldType).toString().indexOf("(")>0) {
                    String width=field.get(fieldType).toString();
                    width=width.substring(width.indexOf("(")+1,width.indexOf(")"));
                    widthMap.put(String.valueOf(field.get(filedName)), Integer.parseInt(width));
                }
            }

        }
        List<Map<String,Object>> listFormInfo=getFormInfo(jsonStr);
        for (int i = 0; i < saveDataArray.size(); i++) {
            JackJSONObject saveData=saveDataArray.getJackJSONObject(i);
            for (int j = 0; j < listFormInfo.size(); j++) {
                Map<String,Object> map=listFormInfo.get(j);
                String isUnique=String.valueOf(map.get("is_unique"));
                String name=String.valueOf(map.get("name"));
                String value=String.valueOf(saveData.get(name));
                if(isUnique.equals("Y")){
                    String dsPkId=String.valueOf(dsMap.get("ds_pk_id"));
                    String pId=String.valueOf(saveData.get(dsPkId));
                    String pageParentUUID=String.valueOf(saveData.get("page_parent_uuid"));
                    String whereSql="";
                    if(!pId.equals("null")&&pId.length()>0){
                        whereSql+=" AND "+dsPkId+"!='"+pId+"'";
                    }
                    if(!pageParentUUID.equals("null")&&pageParentUUID.length()>0){
                        whereSql+=" AND page_parent_uuid='"+pageParentUUID+"'";
                    }
                    String sql="SELECT COUNT(1) FROM "+tableName+" WHERE STATUS=0 AND "+name+"='"+value+"' "+whereSql;
                    Integer count=this.jdbcTemplate.queryForObject(sql,Integer.class);
                    if(count>0){
                        retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("5023")));
                        retJson.put("message",map.get("label_name")+"已存在："+value);
                        return "-1";
                    }
                }
                try {
                    Integer len=widthMap.get(name);
                    if((!value.equals("null"))&&value.length()>len){
                        retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("5022")));
                        retJson.put("message",map.get("label_name")+"："+value+"  超过最大长度："+widthMap.get(name));
                        return "-1";
                    }
                } catch (Exception e) {
                    // text 多行文本 不校验长度
                }
            }
        }
        return "0";
    }

    public String getOrderBySql(String jsonStr, JackJSONObject retJson) {
        JackJSONObject jsonObject = JackJSONObject.fromObject(jsonStr).getJackJSONObject("queryParam");
        try {
            jsonObject.size();
        } catch (Exception e) {
            jsonObject=new JackJSONObject();
        }
        Map<String,Object> dsMap=findDataSourceByJsonStr(jsonStr);
        Map<String,Object> queryMap=getQuery(jsonStr);
        String dsPkId = String.valueOf(dsMap.get("ds_pk_id"));
        String defaultSortType = "desc";
        String sortField = String.valueOf(jsonObject.get("sortField"));
        String sortType = String.valueOf(jsonObject.get("sortType"));
        if ("null".equals(sortField)|| sortField.length() == 0) {
            sortField=String.valueOf(queryMap.get("default_sort_field"));
            if("null".equals(sortField)|| sortField.length() == 0){
                sortField = dsPkId;
            }
        }
        if ("null".equals(sortType)|| sortType.length() == 0) {
            sortType=String.valueOf(queryMap.get("default_sort_type"));
            if("null".equals(sortType)|| sortType.length() == 0){
                sortType = defaultSortType;
            }
        }
        List<Map<String,Object>> fieldList=getQueryInfo(jsonStr);
        Map<String,Object> map=new HashMap<>();
        for (int i = 0; i < fieldList.size(); i++) {
            String fieldName=String.valueOf(fieldList.get(i).get("name"));
            map.put(fieldName,fieldList.get(i));//map里存一份用fieldInfo,fieldName为key
        }
        Map<String,Object> fieldInfo= (Map<String, Object>) map.get(sortField);
        if(fieldInfo!=null){
            String orderBySql = " order by " + sortField + " " + sortType;
            return orderBySql;
        }else{
            retJson.put("status","no_code");
            retJson.put("message","SQL拼接异常，原因是查询组件配置的排序字段不存在（"+sortField+"）");
            return "-1";
        }

    }
    public void getLimitPage(String jsonStr,Map<String,Object> pageMap) {
        JackJSONObject jsonObject = JackJSONObject.fromObject(jsonStr).getJackJSONObject("queryParam");
        try {
            jsonObject.size();
        } catch (Exception e) {
            jsonObject=new JackJSONObject();
        }
        Integer defaultPage = 0;
        Integer defaultPageSize = 10;
        String page = String.valueOf(jsonObject.get("page"));
        String pageSize = String.valueOf(jsonObject.get("pageSize"));
        if ("null".equals(page)|| page.length() == 0) {
            pageMap.put("page",defaultPage);
        }else{
            pageMap.put("page",Integer.valueOf(page));
        }
        if ("null".equals(pageSize)|| pageSize.length() == 0) {
            pageMap.put("pageSize",defaultPageSize);
        }else{
            pageMap.put("pageSize",Integer.valueOf(pageSize));
        }
    }
    public Map<String, Object> getPageInfo(String jsonStr,JackJSONObject retJson, HttpServletRequest request){
        User user=userService.getUser(request);
        JackJSONObject params=JackJSONObject.fromObject(jsonStr);
        String pageCode=String.valueOf(params.get("pageCode"));
        String queryPageSql="SELECT * FROM tbl_data_page WHERE status='0' and page_code='"+pageCode+"'";
        List<Map<String, Object>> pageList=jdbcTemplate.queryForList(queryPageSql);
        if(pageList.size()==0){
            retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("404")));
            retJson.put("message",retJson.get("message"));
            return new HashMap<>();
        }
        String pageId=String.valueOf(pageList.get(0).get("id"));
        String pageParentUuid=String.valueOf(pageList.get(0).get("uuid"));
        String queryPageRoleIdSql="SELECT DISTINCT role_id FROM tbl_data_page_role WHERE page_id="+pageId;
        List<Map<String, Object>> roleIdList=jdbcTemplate.queryForList(queryPageRoleIdSql);
        if(roleIdList.size()>0){
            String whereInSql="";
            for (int i = 0; i < roleIdList.size(); i++) {
                whereInSql+=roleIdList.get(i).get("role_id")+",";
            }
            whereInSql=whereInSql.substring(0,whereInSql.length()-1);
            String countSql="SELECT count(1) FROM tbl_system_roleuser WHERE user_id="+user.getId()+" AND role_id IN ("+whereInSql+")";
            Integer count=jdbcTemplate.queryForObject(countSql,Integer.class);
            if(count==0){
                retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("4031")));
                retJson.put("message",retJson.get("message")+"："+pageCode);
                return new HashMap<>();
            }
        }
        Map<String, Object> retMap=pageList.get(0);
        String queryComponentSql="SELECT * FROM tbl_data_page_component WHERE status='0' and component_status='0' and page_parent_uuid='"+pageParentUuid+"' order by sort asc";
        List<Map<String, Object>> componentList=jdbcTemplate.queryForList(queryComponentSql);
        componentList=filterDataByRole(componentList,request);
        String queryInfoStr=String.valueOf(params.get("queryInfo"));
        String urlWhereSQL="";
        if(!queryInfoStr.equals("null")&&queryInfoStr.length()>0){
            JackJSONObject queryInfo=JackJSONObject.fromObject(queryInfoStr);
            // 遍历并输出所有字段
            for (Object key : queryInfo.keySet()) {
                Object value = queryInfo.get(key);
                urlWhereSQL+=" and "+key+" = '"+value+"'";
            }
        }
        for (int i = 0; i < componentList.size(); i++) {
            String isShowNum=String.valueOf(componentList.get(i).get("is_show_num"));
            if(!isShowNum.equals("Y")){
                continue;
            }
            String showNumDataType=String.valueOf(componentList.get(i).get("show_num_data_type"));
            if(showNumDataType.equals("2")){
                String cSql=String.valueOf(componentList.get(i).get("c_sql"));
                cSql=cSql.replaceAll("&nbsp;"," ");
                cSql=cSql.replaceAll("&quot;","\'");
                cSql=cSql.replace("${user_id}",String.valueOf(user.getId()));
                cSql=cSql.replace("${urlWhereSQL}",urlWhereSQL);
                componentList.get(i).put("sql_value",jdbcTemplate.queryForObject(cSql,String.class));
                continue;
            }
            if(showNumDataType.equals("3")){
                //扩展类
            }
        }
        retMap.put("componentData",componentList);
        return retMap;
    }
    // 根据角色过滤数据
    public List<Map<String, Object>> filterDataByRole(List<Map<String, Object>> dataBefore,HttpServletRequest request){
        return filterDataByRole(dataBefore,request,"view_role_id");
    }
    public List<Map<String, Object>> filterDataByRole(List<Map<String, Object>> dataBefore,HttpServletRequest request,String roleFieldName){
        List<Map<String, Object>> dataAfter=new ArrayList<>();
        if(dataBefore.size()>0){
            User user=userService.getUser(request);
            for (int i = 0; i < dataBefore.size(); i++) {
                String roleStr=String.valueOf(dataBefore.get(i).get(roleFieldName));
                if(roleStr.equals("null")||roleStr.length()==0){ // 空则不控制权限
                    dataAfter.add(dataBefore.get(i));
                }else{
                    String[] roleArr=roleStr.split(",");
                    for (int j = 0; j < roleArr.length; j++) {
                        if(userService.isExistsRole(roleArr[j], user.getId())) {
                            dataAfter.add(dataBefore.get(i));
                            break;
                        }
                    }
                }
            }
        }
        return dataAfter;
    }
    public Map<String, Object> getAllTree(String jsonStr,JackJSONObject retJson, HttpServletRequest request){
        Map<String, Object> retMap=new HashMap<>();
        JackJSONObject queryParamJson=JackJSONObject.fromObject(jsonStr).getJackJSONObject("queryParam");
        try {
            queryParamJson.size();
        } catch (Exception e) {
            return new HashMap<>();
        }
        String treeCode=String.valueOf(JackJSONObject.fromObject(jsonStr).get("treeCode"));
        String queryTreeInfo="SELECT * FROM tbl_data_tree WHERE tree_code='"+treeCode+"'";
        List<Map<String, Object>> treeList=jdbcTemplate.queryForList(queryTreeInfo);
        if(treeList.size()==0){
            retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("7040")));
            retJson.put("message",retJson.get("message")+"treeCode："+treeCode);
            return new HashMap<>();
        }
        khcRedisCache.deleteAllTree();
        String pId=String.valueOf(queryParamJson.get("pId"));
        User user=userService.getUser(request);
        List<Map<String, Object>> treeData= khcRedisCache.getTreeInfoByTreeCodeToList(treeCode,pId,String.valueOf(user.getId()),user);
        retMap.put("treeData",treeData);
        return retMap;
    }

    public Map<String, Object> getAllOutDict(String jsonStr,JackJSONObject retJson, HttpServletRequest request){
        User user=userService.getUser(request);
        Map<String, Object> retMap=new HashMap<>();
        JackJSONObject jsonObject = JackJSONObject.fromObject(jsonStr);
        String oDictCode=String.valueOf(jsonObject.get("oDictCode"));
        String queryDictInfo="SELECT * FROM tbl_data_dict_out WHERE o_dict_code='"+oDictCode+"'";
        List<Map<String, Object>> treeList=jdbcTemplate.queryForList(queryDictInfo);
        if(treeList.size()==0){
            retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("7040")));
            retJson.put("message",retJson.get("message")+"oDictCode："+oDictCode);
            return new HashMap<>();
        }
        retMap.put("oDictCode",oDictCode);
        List<Map<String, Object>> treeData=jdbcTemplate.queryForList(ApiDao.getOutDictWhereSql(oDictCode,jdbcTemplate,user));
        retMap.put("oDictData",treeData);
        return retMap;
    }
    public String getWhereSqlByFieldInfo(String tableSql,List<Map<String,Object>> fieldList, String jsonStr,JdbcTemplate jdbcTemplate,JackJSONObject retJson){
        JackJSONObject queryParamJson=JackJSONObject.fromObject(jsonStr).getJackJSONObject("queryParam");
        try {
            queryParamJson.size();
        } catch (Exception e) {
            return tableSql+" where 1=1 ";//todo 后续需要动态拼接：and status=0
        }
        return ApiDao.getWhereSqlByFieldInfo(tableSql,fieldList,jsonStr,jdbcTemplate,retJson);
    }
    public String getDsTableName(Map<String,Object> dsMap,Map<String,Object> queryMap,User user){
        String isRewriteTableName=String.valueOf(queryMap.get("is_rewrite_table_name"));
        String tableName=String.valueOf(dsMap.get("ds_table_name"));
        if(isRewriteTableName.equals("Y")){//查询组件重写表名SQL
            tableName=String.valueOf(queryMap.get("rewrite_table_name"));
            tableName=tableName.replaceAll("&nbsp;"," ");
            tableName=tableName.replaceAll("&quot;","\'");
            tableName=tableName.replace("${ds_table_name}",String.valueOf(dsMap.get("ds_table_name")));
            if(user!=null){
                tableName=tableName.replace("${user_id}",String.valueOf(user.getId()));
            }
            return tableName;
        }
        isRewriteTableName=String.valueOf(dsMap.get("is_rewrite_table_name"));
        if(isRewriteTableName.equals("Y")){//数据源重写表名SQL
            tableName=String.valueOf(dsMap.get("rewrite_table_name"));
            tableName=tableName.replaceAll("&nbsp;"," ");
            tableName=tableName.replaceAll("&quot;","\'");
            tableName=tableName.replace("${ds_table_name}",String.valueOf(dsMap.get("ds_table_name")));
            if(user!=null){
                tableName=tableName.replace("${user_id}",String.valueOf(user.getId()));
            }
            return tableName;
        }
        return tableName;//都不重写返回数据源配置的表名

    }
    public Map<String,Object> exportExcelDataByXlsx(String jsonStr, JackJSONObject retJson, JtPage jtPage) {
        Map<String,Object>  returnMap=new HashMap<>();
        Map<String,Object>  headMap=new HashMap<>();//作用存标题名称
        List<String> headList = new ArrayList<>();//作用标题排序
        List<Map<String,Object>> fieldList=getQueryInfo(jsonStr);
        Map<String, Object> queryMap=getQuery(jsonStr);
        String queryName= String.valueOf(queryMap.get("query_name"));
        OutputStream stream = null;
        String suffix = ".xlsx";
        DateTime d=new DateTime();
        String preffix = d.toString("yyyyMM")+"/excel_"+UUID.randomUUID().toString().replaceAll("-","");
        List<Map<String,Object>> list=new ArrayList<>();
        // 输出表头
        boolean isExpExeclFiled = false;
        for (int i = 0; i < fieldList.size(); i++) {
            if (fieldList.get(i).get("is_export_excel") != null && String.valueOf(fieldList.get(i).get("is_export_excel")).equals("Y")) {
                isExpExeclFiled = true;
            }
        }
        if(!isExpExeclFiled){
            retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("5030")));
            return new HashMap<>();
        }
        List<Map<String,Object>> dataList =jtPage.getContent();
        ApiDao.exportExcelDataByXlsx(fieldList,headMap,headList,dataList,list,jdbcTemplate);
        try {
            String fileDir=readProperty.getTempFilePath()+d.toString("yyyyMM");
            File folder = new File(fileDir);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            headMap.put("headList",headList);
            stream=new FileOutputStream(readProperty.getTempFilePath()+preffix+suffix);
            ExcelUtil.exportExcelX(queryName,headMap, JackJSONArray.fromObject(list),10,stream);
            returnMap.put("realFileName", queryName+"_数据导出_"+d.toString("yyyyMMddHHmm")+ suffix);
            returnMap.put("diskFileName", preffix + suffix);
            returnMap.put("suffix",  suffix);
            returnMap.put("exportNum",  "共导出："+list.size()+"条");
        } catch (IOException e) {
        }
        return returnMap;
    }
    public Map<String,Object> exportExcelTemplate(List<Map<String,Object>> fieldList,Map<String, Object> queryMap) {
        Map<String,Object>  returnMap=new HashMap<>();
        DateTime d=new DateTime();
        OutputStream stream = null;
        String suffix = ".xls";
        String preffix = "excel_template_"+UUID.randomUUID().toString().replaceAll("-","");
        try {
            stream = new FileOutputStream(readProperty.getTempFilePath()+preffix+suffix);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        ExeclFileObject efo = new ExeclFileObject(stream);
        List<CellForm> cellFormList = new ArrayList<CellForm>();
        List<CellForm> cellFormListField = new ArrayList<CellForm>();
        List<CellForm> cellFormListCity = new ArrayList<CellForm>();
        CellFormat.init();
        int y = 0;
        int yField = 0;
        int yCity = 0;
        // 输出表头
        boolean isExportExeclTemplate = false;
        for (int i = 0; i < fieldList.size(); i++) {
            if (fieldList.get(i).get("is_export_excel_template") != null && fieldList.get(i).get("is_export_excel_template").equals("Y")) {
                isExportExeclTemplate = true;
            }
        }
        if (!isExportExeclTemplate) {
            logger.info("无导出字段");
        } else {
            for (int i = 0; i < fieldList.size(); i++) {
                if (fieldList.get(i).get("is_export_excel_template") != null && fieldList.get(i).get("is_export_excel_template").equals("Y")) {
                    CellForm cellForm = new CellForm();
                    cellForm.setCol(y);
                    cellForm.setRow(0);
                    cellForm.setType(0);
                    cellForm.setHeaderformat(CellFormat.TITLE_HEADER);
                    cellForm.setCellValue(String.valueOf(fieldList.get(i).get("label_name")).replaceAll("\\*", ""));
                    cellFormList.add(cellForm);
                    y++;
                    if((fieldList.get(i).get("dict_code")==null||fieldList.get(i).get("dict_code").equals(""))==false){
                        CellForm cellFormFieldTitle = new CellForm();
                        cellFormFieldTitle.setCol(yField);
                        cellFormFieldTitle.setRow(0);
                        cellFormFieldTitle.setType(0);
                        cellFormFieldTitle.setHeaderformat(CellFormat.TITLE_HEADER);
                        cellFormFieldTitle.setCellValue(String.valueOf(fieldList.get(i).get("label_name")).replaceAll("\\*", ""));
                        cellFormListField.add(cellFormFieldTitle);
                        List<Map<String,Object>> dictList=getDictInfoByDictCodeToList((fieldList.get(i).get("dict_code"))+"");
                        for (int xxx = 0;xxx<dictList.size();xxx++){
                            CellForm cellFormFieldValue = new CellForm();
                            cellFormFieldValue.setCol(yField);
                            cellFormFieldValue.setRow(xxx+1);
                            cellFormFieldValue.setType(0);
                            cellFormFieldValue.setHeaderformat(CellFormat.TITLE_HEADER);
                            cellFormFieldValue.setCellValue(dictList.get(xxx).get("value")+"");
                            cellFormListField.add(cellFormFieldValue);
                        }
                        yField++;
                    }
                }
            }
        }
        try {
            efo.writeSheet(cellFormList, String.valueOf(queryMap.get("query_code")), 0);
            efo.writeSheet(cellFormListField, "内部字典值", 1);
            efo.writeSheet(cellFormListCity, "tree字典（开发中）", 2);
            efo.CloseFile();
            stream.close();
        } catch (Exception e) {
        }
        returnMap.put("realFileName", queryMap.get("query_name")+"数据导入模板_"+ d.toString("yyyyMMddHHmm")+ suffix);
        returnMap.put("diskFileName", preffix + suffix);
        returnMap.put("suffix",  suffix);
        return returnMap;
    }
    //json原始数据导入,excel需要将字典转换，json不需要
    public Map<String,Object> importJsonData(String jsonStr,JackJSONObject retJson,HttpServletRequest request) {
        User user=userService.getUser(request);
        String importJsonStr=getJsonValueByKey(jsonStr,retJson,"importJsonStr");
        JackJSONArray importJsonData=new JackJSONArray();
        try {
            JackJSONArray importJsonArray=JackJSONArray.fromObject(importJsonStr);
            importJsonData=importJsonArray;
        } catch (Exception e) {
            try {
                JackJSONObject importJson=JackJSONObject.fromObject(importJsonStr);
                importJsonData.add(importJson);
            } catch (Exception exception) {
                retJson.put("status","no_code");
                retJson.put("message","导入失败，格式错误");
                return new HashMap<>();
            }
        }
        JackJSONObject jsonObject = JackJSONObject.fromObject(jsonStr);
        String parentUUID=String.valueOf(jsonObject.get("parentUUID"));
        String idValue=String.valueOf(importJsonData.getJackJSONObject(0).get("id"));
        if(!idValue.equals("null")&&idValue.length()>0){
            try {
                Integer.valueOf(idValue);
            } catch (Exception e) {
                retJson.put("status","no_code");
                retJson.put("message","导入失败，id字段必须是数值，请检查数据或联系管理员");
                return new HashMap<>();
            }
        }
        for (int i = 0; i < importJsonData.size(); i++) {
            importJsonData.getJackJSONObject(i).put("data_source","json");
            if(!parentUUID.equals("null")&&parentUUID.length()>0){
                importJsonData.getJackJSONObject(i).put("page_parent_uuid",parentUUID);
            }
        }
        Map<String, Object> dsMap=findDataSourceByJsonStr(jsonStr);
        String tableName=String.valueOf(dsMap.get("ds_table_name"));
        Map<String,Object> saveRetMap=baseService.save(tableName,(List)importJsonData,user);
        if(!"ok".equals(String.valueOf(saveRetMap.get("status")))){
            String filedValue=String.valueOf(saveRetMap.get("fieldValue"));
            String message="导入终止，原因是 ("+saveRetMap.get("fieldName")+"："+saveRetMap.get("fieldName")+") 最大长度为："+saveRetMap.get("maxLength")
                    +"，导入的长度为："+filedValue.length()+"，   原文："+filedValue;
            retJson.put("status","no_code");
            retJson.put("message",message);
            return new HashMap<>();
        }
        retJson.put("status","ok");
        retJson.put("message","导入成功");
        return new HashMap<>();
    }
    public Map<String,Object> updateJsonData(String jsonStr,JackJSONObject retJson,HttpServletRequest request) {
        User user=userService.getUser(request);
        String updateJsonStr=getJsonValueByKey(jsonStr,retJson,"updateJsonStr");
        JackJSONArray updateJsonData=new JackJSONArray();
        try {
            JackJSONArray updateJsonArray=JackJSONArray.fromObject(updateJsonStr);
            updateJsonData=updateJsonArray;
        } catch (Exception e) {
            try {
                JackJSONObject importJson=JackJSONObject.fromObject(updateJsonStr);
                updateJsonData.add(importJson);
            } catch (Exception exception) {
                retJson.put("status","no_code");
                retJson.put("message","更新失败，格式错误");
                return new HashMap<>();
            }
        }
        JackJSONObject jsonObject = JackJSONObject.fromObject(jsonStr);
        String parentUUID=String.valueOf(jsonObject.get("parentUUID"));
        String idValue=String.valueOf(updateJsonData.getJackJSONObject(0).get("id"));
        if(!idValue.equals("null")&&idValue.length()>0){
            try {
                Integer.valueOf(idValue);
            } catch (Exception e) {
                retJson.put("status","no_code");
                retJson.put("message","更新失败，id字段必须是数值，请检查数据或联系管理员");
                return new HashMap<>();
            }
        }
        for (int i = 0; i < updateJsonData.size(); i++) {
            updateJsonData.getJackJSONObject(i).put("data_source","json");
            if(!parentUUID.equals("null")&&parentUUID.length()>0){
                updateJsonData.getJackJSONObject(i).put("page_parent_uuid",parentUUID);
            }
        }
        Map<String, Object> dsMap=findDataSourceByJsonStr(jsonStr);
        String tableName=String.valueOf(dsMap.get("ds_table_name"));
        baseService.update(tableName,(List)updateJsonData,user);
        retJson.put("status","ok");
        retJson.put("message","更新成功");
        return new HashMap<>();
    }


    public Map<String,Object> importExcelData(JackJSONObject retJson,HttpServletRequest request) {
        Map<String,Object>  returnMap=new HashMap<>();
        Map<String,Object> fileInfo=null;
        try {

            Map<String,Object> uploadFile=uploadToService(retJson,request);
            fileInfo= (Map<String, Object>) uploadFile.get("fileInfo");
            String jsonStr=request.getParameter("data");
            Map<String, Object> dsMap=findDataSourceByJsonStr(jsonStr);
            List<Map<String, Object>> queryFieldList=getQueryInfo(jsonStr);
            List<Map<String, Object>> formFieldList=getFormInfo(jsonStr);
            File file=new File(readProperty.getTempFilePath()+fileInfo.get("diskFileName"));
            //以下是获取excel内的信息 读取信息循环
            InputStream inputStream = new FileInputStream(file);
            String suffix=String.valueOf(fileInfo.get("suffix"));
            if(!"xls".equals(suffix)&&!"xlsx".equals(suffix)){
                retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("5040")));
                retJson.put("message",retJson.get("message")+" 你导入的文件格式是："+suffix);
                retJson.put("fileInfo",fileInfo);
                return new HashMap<>();
            }
            String tableName=String.valueOf(dsMap.get("ds_table_name"));
            Map<String,Object> labelNameMap=new HashMap<>();
            for (int i = 0; i < queryFieldList.size(); i++) {
                String key=String.valueOf(queryFieldList.get(i).get("name"));
                labelNameMap.put(key,queryFieldList.get(i).get("label_name"));
            }
            List<Map<String, Object>> dataMaps=new ArrayList<>();
            User user=userService.getUser(request);
            returnMap= ApiDao.importExcelData("",retJson,returnMap,fileInfo,dataMaps,queryFieldList,formFieldList,inputStream,userService,user,jdbcTemplate,redisPublication);
            if(returnMap.size()==0){
                return new HashMap<>();
            }
            JackJSONObject jsonObject = JackJSONObject.fromObject(jsonStr);
            String wsCode=String.valueOf(jsonObject.get("queryCode"));
            Map<String,Object> saveRetMap=baseService.save(tableName,dataMaps);
            if(!"ok".equals(String.valueOf(saveRetMap.get("status")))){
                String message="导入终止,原因是 "+labelNameMap.get(saveRetMap.get("fieldName"))+"("+saveRetMap.get("fieldName")+") 最大长度为："+saveRetMap.get("maxLength")+",导入的长度为："+String.valueOf(saveRetMap.get("fieldValue")).length();
                redisPublication.sendMessage("{\"wsCode\":\""+wsCode+"\",\"message\":\""+message+"\",\"status\":\"5010\",\"isHideMask\":\"Y\"}",String.valueOf(user.getId()));
                return new HashMap<>();
            }
            redisPublication.sendMessage("{\"wsCode\":\""+wsCode+"\",\"message\":\""+returnMap.get("importMessage")+"\",\"status\":\"ok\",\"isHideMask\":\"Y\"}",String.valueOf(user.getId()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        returnMap.put("fileInfo",fileInfo);
        return returnMap;
    }
    /**
     * 支持xls和xlsx导入
     */
    public Map<String,Object> importExcelDataNew(String jsonStr,JackJSONObject retJson,HttpServletRequest request,User user) {
        Map<String,Object>  returnMap=new HashMap<>();
        Map<String,Object> fileInfo=null;
        try {
            JackJSONArray fileArray=JackJSONArray.fromObject(getJsonValueByKey(jsonStr,retJson,"fileArray"));
            fileInfo=fileArray.getJackJSONObject(0);
            Map<String, Object> dsMap=findDataSourceByJsonStr(jsonStr);
            List<Map<String, Object>> queryFieldList=getQueryInfo(jsonStr);
            List<Map<String, Object>> formFieldList=getFormInfo(jsonStr);
            File file=new File(readProperty.getTempFilePath()+fileInfo.get("diskFileName"));
            //以下是获取excel内的信息 读取信息循环
            InputStream inputStream = new FileInputStream(file);
            String suffix=String.valueOf(fileInfo.get("suffix"));
            if(!"xls".equals(suffix)&&!"xlsx".equals(suffix)){
                retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("5040")));
                retJson.put("message",retJson.get("message")+" 你导入的文件格式是："+suffix);
                retJson.put("fileInfo",fileInfo);
                return new HashMap<>();
            }
            String tableName=String.valueOf(dsMap.get("ds_table_name"));
            Map<String,Object> labelNameMap=new HashMap<>();
            for (int i = 0; i < queryFieldList.size(); i++) {
                String key=String.valueOf(queryFieldList.get(i).get("name"));
                labelNameMap.put(key,queryFieldList.get(i).get("label_name"));
            }
            List<Map<String, Object>> dataMaps=new ArrayList<>();
            returnMap= ApiDao.importExcelData(jsonStr,retJson,returnMap,fileInfo,dataMaps,queryFieldList,formFieldList,inputStream,userService,user,jdbcTemplate,redisPublication);
            if(returnMap.size()==0){
                return new HashMap<>();
            }
            Map<String,Object> defaultMap=new HashMap<>();
            if(dataMaps.size()>0){
                if(formFieldList.size()>0){//遍历表单获取默认值
                    for (int i = 0; i < formFieldList.size(); i++) {
                        String defaultValue=String.valueOf(formFieldList.get(i).get("default_value"));
                        if(!defaultValue.equals("null")&&defaultValue.length()>0){
                            String fieldName=String.valueOf(formFieldList.get(i).get("name"));
                            defaultMap.put(fieldName,defaultValue);
                        }
                    }
                    if(defaultMap.size()>0){
                        for (int i = 0; i < dataMaps.size(); i++) {
                            Map<String, Object> currentMap = dataMaps.get(i);

                            for (Map.Entry<String, Object> entry : defaultMap.entrySet()) {
                                String key = entry.getKey();
                                Object defaultValue = entry.getValue();

                                String dataValue=String.valueOf(currentMap.get(key));
                                if (dataValue.equals("null")||dataValue.length()==0) {
                                    currentMap.put(key, defaultValue);
                                }
                            }
                        }
                    }
                }
            }
            JackJSONObject jsonObject = JackJSONObject.fromObject(jsonStr);
            String wsCode=String.valueOf(jsonObject.get("queryCode"));
            long startTime = System.currentTimeMillis();//获取开始时间
            Map<String,Object> saveRetMap=baseService.save(tableName,dataMaps,redisPublication,wsCode,user);
            if(!"ok".equals(String.valueOf(saveRetMap.get("status")))){
                String filedValue=String.valueOf(saveRetMap.get("fieldValue"));
                if(filedValue.length()>500){
                    filedValue = filedValue.substring(0, Math.min(filedValue.length(), 500))+"...";
                }
                filedValue = filedValue.replaceAll("[\n\r]", " ");//打印这个如果有特殊字符会影响json格式
                String message="导入终止，原因是 ("+labelNameMap.get(saveRetMap.get("fieldName"))+"："+saveRetMap.get("fieldName")+") 最大长度为："+saveRetMap.get("maxLength")
                        +"，导入的长度为："+saveRetMap.get("fieldLength");
                redisPublication.sendMessage("{\"wsCode\":\""+wsCode+"\",\"message\":\""+message+"\",\"status\":\"5010\",\"isHideMask\":\"Y\"}",String.valueOf(user.getId()));
                return new HashMap<>();
            }
            String importMessage=returnMap.get("importMessage")+"，用时："+(System.currentTimeMillis() - startTime)+"毫秒";
            redisPublication.sendMessage("{\"wsCode\":\""+wsCode+"\",\"message\":\""+importMessage+"\",\"status\":\"ok\",\"isHideMask\":\"Y\"}",String.valueOf(user.getId()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        returnMap.put("fileInfo",fileInfo);
        return returnMap;
    }
    /**
     * 文件上传本地服务器
     */
    public Map<String,Object> uploadToService(JackJSONObject retJson,HttpServletRequest request) {
        Map<String,Object>  returnMap=new HashMap<>();
        Map<String,Object> fileInfo=ApiDao.uploadToService(readProperty.getTempFilePath(), request);
        returnMap.put("fileInfo",fileInfo);
        return returnMap;
    }
    /**
     * 文件上传Minio
     */
    public Map<String,Object> uploadToMinio(JackJSONObject retJson,HttpServletRequest request) {
        Map<String,Object>  returnMap=new HashMap<>();
        Map<String,Object> fileInfo=ApiDao.uploadToMinio(retJson,minioService, request);
        if(fileInfo.size()==0){
            return new HashMap<>();
        }
        returnMap.put("fileInfo",fileInfo);
        return returnMap;
    }
    public Map<String,Object> createOnePdf(String jsonStr,JackJSONObject retJson,HttpServletRequest request) {
        User user=userService.getUser(request);
        Map<String,Object>  returnMap=new HashMap<>();
        List<Map<String,Object>> fieldList=getFormInfo(jsonStr);
        Map<String, Object> dsMap=findDataSourceByJsonStr(jsonStr);
        Map<String, Object> formMap=getForm(jsonStr);
        //todo-hui 这里应该加个before方便扩展，暂时写死 page_parent_uuid
        String pageParentUuid=String.valueOf(formMap.get("uuid"));
        String queryTemplateSql="SELECT * FROM tbl_data_pdf_template where page_parent_uuid='"+pageParentUuid+"'";
        List<Map<String,Object>> pdfTemplateList=jdbcTemplate.queryForList(queryTemplateSql);
        String pkId=getJsonValueByKey(jsonStr,retJson,"pkId");
        String querySql="SELECT * FROM "+dsMap.get("ds_table_name")+" where id='"+pkId+"'";
        List<Map<String,Object>> dataList=jdbcTemplate.queryForList(querySql);
        Map<String,Object> pdfTemplate;
        if(pdfTemplateList.size()==0){
            retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("6050")));
            retJson.put("message",retJson.get("message"));
            return new HashMap<>();
        }else{
            pdfTemplate=pdfTemplateList.get(0);
        }
        dataList=ApiDao.changeFormDict(fieldList,dataList,jdbcTemplate);
        String pdfTemplateHTML="";
        String pdfTemplateType=String.valueOf(pdfTemplate.get("pdf_template_type"));
        if(!"null".equals(pdfTemplateType)&&pdfTemplateType.equals("default")){//默认模板
            pdfTemplateHTML= BaseConfigStaticCache.get(SYSTEM_SETTINGS_DS_FORM_PDF_TEMPLATE);
            pdfTemplateHTML=pdfTemplateHTML.replaceAll("&nbsp;"," ");
            String defaultValue=ApiDao.createOnePdfDefaultHtml(fieldList,dataList,jdbcTemplate);
            pdfTemplateHTML=pdfTemplateHTML.replaceAll("\\$\\{defaultTemplate\\}",defaultValue);
            for (String key : pdfTemplate.keySet()) {
                String oldStr="\\$\\{"+key+"\\}";
                String newStr=pdfTemplate.get(key)+"";
                pdfTemplateHTML=pdfTemplateHTML.replaceAll(oldStr,newStr);
            }
        }else{//自定义模板
            pdfTemplateHTML=String.valueOf(pdfTemplate.get("pdf_template"));
            if("null".equals(pdfTemplateHTML)||pdfTemplateHTML.length()==0){
                retJson.putAll(JackJSONObject.fromObject(getReturnDataByCode("6050")));
                retJson.put("message",retJson.get("message"));
                return new HashMap<>();
            }
            pdfTemplateHTML=pdfTemplateHTML.replaceAll("&nbsp;"," ");
            pdfTemplateHTML=pdfTemplateHTML.replaceAll("&quot;","'");
            for (int i = 0; i < fieldList.size(); i++) {
                String oldStr="\\$\\{"+fieldList.get(i).get("name")+"\\}";
                String newStr=dataList.get(0).get(fieldList.get(i).get("name"))+"";
                pdfTemplateHTML=pdfTemplateHTML.replaceAll(oldStr,newStr);
            }
            pdfTemplateHTML=TemplateReplace.renderTemplate(pdfTemplateHTML,dataList.get(0));
            for (String key : pdfTemplate.keySet()) {
                String oldStr="\\$\\{"+key+"\\}";
                String newStr=pdfTemplate.get(key)+"";
                pdfTemplateHTML=pdfTemplateHTML.replaceAll(oldStr,newStr);
            }
        }
        //替换内容后 再次处理一下空格和单引号
        pdfTemplateHTML=pdfTemplateHTML.replaceAll("&nbsp;"," ");
        pdfTemplateHTML=pdfTemplateHTML.replaceAll("&quot;","'");
        String suffix = ".pdf";
        DateTime d=new DateTime();
        String preffix = d.toString("yyyyMM")+"/pdf_"+UUID.randomUUID().toString().replaceAll("-","");
        String fileDir=readProperty.getTempFilePath()+d.toString("yyyyMM");
        File folder = new File(fileDir);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        File f=new File(readProperty.getTempFilePath()+preffix+suffix);
        try {
            OutputStream os = new FileOutputStream(f);
            ITextRenderer renderer = new ITextRenderer();
            ITextFontResolver fontResolver = renderer.getFontResolver();
            fontResolver.addFont(readProperty.getFontFilePath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            renderer.setDocumentFromString(pdfTemplateHTML);
            renderer.layout();
            renderer.createPDF(os);
            os.flush();
            os.close();
            FileInputStream inputStream = new FileInputStream(f);
            byte[] data = new byte[(int) f.length()];
            inputStream.read(data);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String fileNameDate="";
        String pattern=String.valueOf(pdfTemplate.get("file_name_date"));
        String waterMark=String.valueOf(pdfTemplate.get("water_mark"));
        if(!"null".equals(pattern)&&pattern.length()>0){
            fileNameDate=d.toString(pattern);
        }
        if(!"null".equals(waterMark)&&waterMark.length()>0){
            try {
                waterMark=waterMark.replace("${user_name}",user.getUserName());
                PdfAddWaterMarkUtil.addPDFWaterMark(readProperty.getTempFilePath()+preffix+suffix,readProperty.getTempFilePath()+preffix +"_water_mark"+suffix,waterMark);
                returnMap.put("diskFileName", pdfTemplate.get("file_name")+ fileNameDate +"_water_mark"+ suffix);
                returnMap.put("realFileName", preffix +"_water_mark"+ suffix);
            } catch (Exception e) {
                returnMap.put("realFileName", preffix + suffix);
                returnMap.put("diskFileName", pdfTemplate.get("file_name")+ fileNameDate + suffix);
            }
        }else{
            returnMap.put("realFileName", preffix + suffix);
            returnMap.put("diskFileName", pdfTemplate.get("file_name")+ fileNameDate + suffix);
        }
        returnMap.put("suffix",  suffix);
        returnMap.put("exportNum",  "导出成功");
        return returnMap;
    }
    public Map<String,Object> createWord(String jsonStr,JackJSONObject retJson, HttpServletRequest request,Map<String,Object> dataMap) {
        User user=userService.getUser(request);
        Map<String,Object> returnMap=new HashMap<>();
        Map<String,Object> queryMap=getQuery(jsonStr);
        String wordTemplate=String.valueOf(queryMap.get("word_template"));
        JackJSONArray jsonArray=JackJSONArray.fromObject(wordTemplate);
        if(jsonArray.size()>0){
            String realFileName =String.valueOf(jsonArray.getJackJSONObject(0).get("realFileName"));
            String suffix =String.valueOf(jsonArray.getJackJSONObject(0).get("suffix"));
            String diskFileName =String.valueOf(jsonArray.getJackJSONObject(0).get("diskFileName"));
            String oldTemplatePath= readProperty.getUploadFilePath()+diskFileName;//最初的模板，不可在此模板基础上做任何修改，只能拷贝出一个副本来修改
            String uuid=UUID.randomUUID().toString().replaceAll("-","");
            String newTemplatePath=readProperty.getTempFilePath()+uuid+"."+suffix;//拷贝出来后的模板
            try {
                FileInputStream fis = new FileInputStream(new File(oldTemplatePath));
                File newFile=new File(newTemplatePath);
                //判断文件是否存在
                if (!newFile.exists()) {
                    //创建文件
                    newFile.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(newFile);
                byte b[] = new byte[1024];
                int len=0;
                while((len=fis.read(b))!=-1){
                    fos.write(b);
                }
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            /**
             * 前后缀 官方使用 {{}} 的方式来致敬Google CTemplate，如果你更偏爱freemarker ${} 的方式：
             * Configure config=Configure.builder().buildGramer("${", "}").build();
             */
            String poiConfigureStr=String.valueOf(dataMap.get("poiConfigure"));
            XWPFTemplate template;
            if(!poiConfigureStr.equals("null")&&poiConfigureStr.length()>0){
                Configure config = (Configure) dataMap.get("poiConfigure");
                template = XWPFTemplate.compile(newTemplatePath,config).render(dataMap);
            }else{
                template = XWPFTemplate.compile(newTemplatePath).render(dataMap);
            }
            String tempPath=readProperty.getUploadFilePath();
            String outTempFileName=UUID.randomUUID().toString().replaceAll("-","");
            returnMap.put("uuid", outTempFileName);
            try {
                template.writeToFile(tempPath+outTempFileName+"."+suffix);
                returnMap.put("source", "service");
                String wordWaterMark=String.valueOf(queryMap.get("word_template_water_mark"));
                if(!"null".equals(wordWaterMark)&&wordWaterMark.length()>0){
                    wordWaterMark=wordWaterMark.replace("${user_name}",user.getUserName());
                    WordAddWaterMarkUtil.addWordWaterMark(tempPath+outTempFileName+"."+suffix,tempPath+outTempFileName+"_word_template_water_mark"+"."+suffix,wordWaterMark);
                    returnMap.put("diskFileName", outTempFileName+"_word_template_water_mark"+"."+suffix);
                }else{
                    returnMap.put("diskFileName", outTempFileName+"."+suffix);
                }
                returnMap.put("realFileName", realFileName);
                returnMap.put("suffix",  suffix);
                returnMap.put("exportNum",  "导出成功");
            } catch (IOException e) {
                //异常处理
                e.printStackTrace();
            }
        }else{
            retJson.put("status","no_code");
            retJson.put("message","未上传word模板");
            return new HashMap<>();
        }

        return returnMap;
    }
    public Map<String,Object> createExcel(String jsonStr,JackJSONObject retJson, HttpServletRequest request,Map<String,Object> dataMap) {
        User user=userService.getUser(request);
        Map<String,Object> returnMap=new HashMap<>();
        Map<String,Object> queryMap=getQuery(jsonStr);
        String excelOneTemplate=String.valueOf(queryMap.get("excel_one_template"));
        JackJSONArray jsonArray=JackJSONArray.fromObject(excelOneTemplate);
        if(jsonArray.size()>0){
            String realFileName =String.valueOf(jsonArray.getJackJSONObject(0).get("realFileName"));
            String suffix =String.valueOf(jsonArray.getJackJSONObject(0).get("suffix"));
            String diskFileName =String.valueOf(jsonArray.getJackJSONObject(0).get("diskFileName"));
            String oldTemplatePath= readProperty.getUploadFilePath()+diskFileName;//最初的模板，不可在此模板基础上做任何修改，只能拷贝出一个副本来修改
            String uuid=UUID.randomUUID().toString().replaceAll("-","");
            String newTemplatePath=readProperty.getTempFilePath()+uuid+"."+suffix;//拷贝出来后的模板
            try {
                FileInputStream fis = new FileInputStream(new File(oldTemplatePath));
                File newFile=new File(newTemplatePath);
                //判断文件是否存在
                if (!newFile.exists()) {
                    //创建文件
                    newFile.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(newFile);
                byte b[] = new byte[1024];
                int len=0;
                while((len=fis.read(b))!=-1){
                    fos.write(b);
                }
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            String tempPath=readProperty.getUploadFilePath();
            String fileName=UUID.randomUUID().toString().replaceAll("-","");
            returnMap.put("uuid", fileName);
            String outTempFileName=fileName+"."+suffix;
            String outTempPathFileName=tempPath+outTempFileName ;
            ExcelOneUtil.exportExcel(newTemplatePath,outTempPathFileName,dataMap);
            String excelWaterMark=String.valueOf(queryMap.get("excel_template_water_mark"));
            if(!"null".equals(excelWaterMark)&&excelWaterMark.length()>0){
                excelWaterMark=excelWaterMark.replace("${user_name}",user.getUserName());
                ExcelWaterRemarkUtils.addExcelWaterMark(outTempPathFileName,tempPath+fileName+"excel_template_water_mark"+"."+suffix,excelWaterMark);
                returnMap.put("diskFileName", fileName+"excel_template_water_mark"+"."+suffix);
            }else{
                returnMap.put("diskFileName", outTempFileName);
            }
            returnMap.put("source", "service");
            returnMap.put("realFileName", realFileName);
            returnMap.put("suffix",  suffix);
            returnMap.put("exportNum",  "导出成功");
        }else{
            retJson.put("status","no_code");
            retJson.put("message","未上传Excel-one模板");
            return new HashMap<>();
        }

        return returnMap;
    }
    public void refreshChildLevel(Map<String,Object> map){
        String pIdField=String.valueOf(map.get("pIdField"));
        String pId=String.valueOf(map.get(pIdField));
        String idField=String.valueOf(map.get("idField"));
        String tableName=String.valueOf(map.get("tableName"));
        String levelField=String.valueOf(map.get("levelField"));
        Integer level=Integer.parseInt(String.valueOf(map.get(levelField)));
        String sql="SELECT * FROM "+tableName+" WHERE "+pIdField+"='"+pId+"'";
        List<Map<String, Object>> list=jdbcTemplate.queryForList(sql);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).put(levelField,level);
            baseService.update(tableName,list.get(i));
            map.put(pIdField,String.valueOf(list.get(i).get(idField)));
            map.put(levelField,level+1);
            refreshChildLevel(map);
        }
    }

    public Map<String,Object> valueToShowValue(String jsonStr, HttpServletRequest request, Map<String,Object> map){
        List<Map<String,Object>> fieldList=getQueryInfo(jsonStr);
        List<Map<String,Object>> dataList=new ArrayList<>();
        dataList.add(map);
        dataList=ApiDao.changeFormDict(fieldList,dataList,jdbcTemplate);
        return dataList.get(0);
    }

    public JtPage valueRewrite(String jsonStr, HttpServletRequest request, JtPage jtPage){
        if(jtPage.getContent().size()==0){
            return jtPage;
        }
        List<Map<String,Object>> fieldList=getQueryInfo(jsonStr);
        Map<String,Object> reWriteConfigMap=new HashMap<>();
        for (int i = 0; i < fieldList.size(); i++) {//这个循环是提前将dict字典查询出来，避免每次循环都查询数据库
            String isQueryAfterRewriteValue=String.valueOf(fieldList.get(i).get("is_query_after_rewrite_value"));
            String name=String.valueOf(fieldList.get(i).get("name"));
            if(!"null".equals(isQueryAfterRewriteValue)&&isQueryAfterRewriteValue.length()>0&&isQueryAfterRewriteValue.equals("Y")){
                reWriteConfigMap.put(name,fieldList.get(i));
            }
        }
        for (String key : reWriteConfigMap.keySet()) {
            for (int i = 0; i < jtPage.getContent().size(); i++) {
                Map<String,Object> content=jtPage.getContent().get(i);
                Map<String,Object> fieldInfo= (Map<String, Object>) reWriteConfigMap.get(key);
                String queryAfterRewriteSql=String.valueOf(fieldInfo.get("query_after_rewrite_sql"));
                String queryAfterRewriteSqlReturnType=String.valueOf(fieldInfo.get("query_after_rewrite_sql_return_type"));
                queryAfterRewriteSql=queryAfterRewriteSql.replaceAll("&nbsp;"," ");
                queryAfterRewriteSql=queryAfterRewriteSql.replaceAll("&quot;","'");
                for (String fieldName : content.keySet()) {
                    String oldStr="\\$\\{"+fieldName+"\\}";
                    String newStr=content.get(fieldName)+"";
                    queryAfterRewriteSql=queryAfterRewriteSql.replaceAll(oldStr,newStr);
                }
                if(queryAfterRewriteSqlReturnType.equals("1")){
                    try {
                        jtPage.getContent().get(i).put(key,jdbcTemplate.queryForObject(queryAfterRewriteSql,String.class));
                    } catch (DataAccessException e) {
                        jtPage.getContent().get(i).put(key,"");
                    }
                }
                if(queryAfterRewriteSqlReturnType.equals("2")){
                    jtPage.getContent().get(i).put(key,jdbcTemplate.queryForMap(queryAfterRewriteSql));
                }
                if(queryAfterRewriteSqlReturnType.equals("3")){
                    jtPage.getContent().get(i).put(key,jdbcTemplate.queryForList(queryAfterRewriteSql));
                }
            }
        }
        return jtPage;
    }
    public Map<String,Object> valueRewrite(String jsonStr, HttpServletRequest request, Map<String,Object> content){
        List<Map<String,Object>> fieldList=getQueryInfo(jsonStr);
        Map<String,Object> reWriteConfigMap=new HashMap<>();
        for (int i = 0; i < fieldList.size(); i++) {//这个循环是提前将dict字典查询出来，避免每次循环都查询数据库
            String isQueryAfterRewriteValue=String.valueOf(fieldList.get(i).get("is_query_after_rewrite_value"));
            String name=String.valueOf(fieldList.get(i).get("name"));
            if(!"null".equals(isQueryAfterRewriteValue)&&isQueryAfterRewriteValue.length()>0&&isQueryAfterRewriteValue.equals("Y")){
                reWriteConfigMap.put(name,fieldList.get(i));
            }
        }
        for (String key : reWriteConfigMap.keySet()) {
            Map<String,Object> fieldInfo= (Map<String, Object>) reWriteConfigMap.get(key);
            String queryAfterRewriteSql=String.valueOf(fieldInfo.get("query_after_rewrite_sql"));
            String queryAfterRewriteSqlReturnType=String.valueOf(fieldInfo.get("query_after_rewrite_sql_return_type"));
            queryAfterRewriteSql=queryAfterRewriteSql.replaceAll("&nbsp;"," ");
            queryAfterRewriteSql=queryAfterRewriteSql.replaceAll("&quot;","'");
            for (String fieldName : content.keySet()) {
                String oldStr="\\$\\{"+fieldName+"\\}";
                String newStr=content.get(fieldName)+"";
                queryAfterRewriteSql=queryAfterRewriteSql.replaceAll(oldStr,newStr);
            }
            if(queryAfterRewriteSqlReturnType.equals("1")){
                content.put(key,jdbcTemplate.queryForObject(queryAfterRewriteSql,String.class));
            }
            if(queryAfterRewriteSqlReturnType.equals("2")){
                content.put(key,jdbcTemplate.queryForMap(queryAfterRewriteSql));
            }
            if(queryAfterRewriteSqlReturnType.equals("3")){
                content.put(key,jdbcTemplate.queryForList(queryAfterRewriteSql));
            }
        }
        return content;
    }

    public void executeJobByMethodName(String jobClassPath, Map<String,Object> dsMap,Map<String,Object> dataMap,String methodName){
        try {
            // 1. 加载类
            Class<?> jobClass = Class.forName(jobClassPath);

            // 2. 创建类的实例
            Object jobInstance = jobClass.getDeclaredConstructor().newInstance();

            // 3. 获取 `methodName` 方法（带有 Map<String, Object> 和 Map<String, Object> 参数）
            Method initMethod = jobClass.getMethod(methodName, Map.class, Map.class);

            // 4. 调用 `methodName` 方法
            initMethod.invoke(jobInstance, dsMap, dataMap);

        } catch (ClassNotFoundException e) {
            System.err.println("类路径错误，未找到类: " + jobClassPath);
        } catch (NoSuchMethodException e) {
            System.err.println("找不到 "+methodName+" 方法，请确保该方法存在并且参数正确。");
        } catch (Exception e) {
            System.err.println("调用 "+methodName+" 方法时发生错误: " + e.getMessage());
        }
    }

}
