package cn.com.capcloud.api.action.myself.system.data;

import cn.com.capcloud.api.action.service.ApiDao;
import cn.com.capcloud.api.action.service.ApiService;
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.cache.KHCRedisCache;
import cn.com.capcloud.core.lucene.LuceneIndexManager;
import cn.com.capcloud.core.noentitydb.*;
import cn.com.capcloud.core.cache.BaseConfigStaticCache;
import cn.com.capcloud.core.quartz.task.DataSourceJobRunner;
import cn.com.capcloud.core.system.user.UserService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

@Component
public class DataSourceAction extends DefaultAction {
    //工作流的一些默认字段(KEY)
    private static final String SYSTEM_SETTINGS_DS_BPM_FIELD_JSON="system.settings.ds.bpm.field.json";
    //查询组件的默认数据(KEY)
    private static final String SYSTEM_SETTINGS_DS_QUERY_JSON="system.settings.ds.query.json";
    //表单组件的默认数据(KEY)
    private static final String SYSTEM_SETTINGS_DS_FORM_JSON="system.settings.ds.form.json";
    //查询按钮组件的默认数据(KEY)
    private static final String SYSTEM_SETTINGS_DS_QUERY_BUTTON_JSON="system.settings.ds.query.button.json";
    //表单按钮组件的默认数据(KEY)
    private static final String SYSTEM_SETTINGS_DS_FORM_BUTTON_JSON="system.settings.ds.form.button.json";
    @Resource
    private BaseService baseService;
    @Resource
    private UserService userService;
    @Resource
    private ApiService apiService;
    @Resource
    private LuceneIndexManager luceneIndexManager;
    @Resource
    private KHCRedisCache khcRedisCache;
    // 使用 @Value 注解从配置文件中获取值
    @Value("${rzth.isRunTask}")
    private String isRunTask;
    @Resource
    private DataVmTableAction dataVmTableAction;
    private static DataSourceAction action;
    @PostConstruct
    public void init(){
        action=this;
        action.baseService=this.baseService;
        action.userService=this.userService;
        action.apiService =this.apiService;
        action.dataVmTableAction=this.dataVmTableAction;
        action.luceneIndexManager=this.luceneIndexManager;
        action.khcRedisCache =this.khcRedisCache;
    }

    @Override
    public JackJSONArray saveBefore(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JackJSONArray array) {
        for (int i = 0; i < array.size(); i++) {
            String id=String.valueOf(array.getJackJSONObject(i).get("id"));
            String dsCode=String.valueOf(array.getJackJSONObject(i).get("ds_code"));
            String enableHistory=String.valueOf(array.getJackJSONObject(i).get("enable_history"));
            String tableName=String.valueOf(array.getJackJSONObject(i).get("ds_table_name"));
            if("null".equals(id)||id.length()==0){
                String sql="SELECT COUNT(1) FROM tbl_data_source WHERE ds_code='"+dsCode+"'";
                Integer count=this.getJdbcTemplate().queryForObject(sql,Integer.class);
                if(count>0){
                    retJson.putAll(JackJSONObject.fromObject(action.apiService.getReturnDataByCode("6031")));
                    retJson.put("message",retJson.get("message")+" ds_code："+dsCode);
                    return new JackJSONArray();
                }
            }
            if(enableHistory.equals("Y")){
                List<Map<String,Object>> listMap = BaseDao.getAllCommentsByTableName(tableName, this.getJdbcTemplate());
                Map<String,Object> filedMap=new HashMap<>();
                for(int j=0;j<listMap.size();j++) {
                    String key=String.valueOf(listMap.get(j).get("Field"));
                    filedMap.put(key,key);
                }
                String isHistory = String.valueOf(filedMap.get("is_history"));
                String uuid = String.valueOf(filedMap.get("uuid"));
                String pageParentUuid = String.valueOf(filedMap.get("page_parent_uuid"));
                if(isHistory.equals("null")||isHistory.length()==0){
                    retJson.put("status","no_code");
                    retJson.put("message","保存失败，原因是：启用历史功能需要 is_history 字段");
                    return new JackJSONArray();
                }
                if(uuid.equals("null")||uuid.length()==0){
                    retJson.put("status","no_code");
                    retJson.put("message","保存失败，原因是：启用历史功能需要 uuid 字段");
                    return new JackJSONArray();
                }
                if(pageParentUuid.equals("null")||pageParentUuid.length()==0){
                    retJson.put("status","no_code");
                    retJson.put("message","保存失败，原因是：启用历史功能需要 page_parent_uuid 字段");
                    return new JackJSONArray();
                }
            }
            array.getJackJSONObject(i).remove("query_data");
            array.getJackJSONObject(i).remove("form_data");
        }
        return array;
    }

    @Override
    public JackJSONArray saveAfter(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JackJSONArray array) {
        for (int i = 0; i < array.size(); i++) {
            String dsCode=String.valueOf(array.getJackJSONObject(i).get("ds_code"));
            Map<String,Object> dsMap=action.apiService.findDataSourceByCode(dsCode);
            String countSql="SELECT count(1) FROM tbl_data_form WHERE page_parent_uuid='"+dsMap.get("uuid")+"' AND is_bpm_model='Y' AND bpm_model_id>0";
            Integer count=this.getJdbcTemplate().queryForObject(countSql,Integer.class);
            String tableName=String.valueOf(dsMap.get("ds_table_name"));
            if(count>0){
                List<Map<String,Object>> tableList=this.getJdbcTemplate().queryForList("SHOW TABLES LIKE '"+tableName+"'");
                if(tableList.size()>0){//表已创建再追加工作流字段
                    initBpmField(tableName);
                }
            }
            String isLucene=String.valueOf(dsMap.get("is_lucene"));
            if(isLucene.equals("Y")){
                try {
                    action.luceneIndexManager.reInitLuceneDir();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(isRunTask.equals("Y")){
                String enableJob=String.valueOf(dsMap.get("enable_job"));
                String jobClassPath=String.valueOf(dsMap.get("job_class_path"));
                if(!jobClassPath.equals("null")&&jobClassPath.length()>0){
                    if(enableJob.equals("Y")){
                        DataSourceJobRunner.executeJobAllByMethodName(jobClassPath,this.getJdbcTemplate(),dsMap,"startAll");
                    }else{
                        DataSourceJobRunner.executeJobAllByMethodName(jobClassPath,this.getJdbcTemplate(),dsMap,"stopAll");
                    }
                }
            }
        }
        return super.saveAfter(jsonStr, retJson, request, array);
    }

    public JtPage dataSourceShowAllAfter(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JtPage jtPage) {
        for (int i = 0; i < jtPage.getContent().size(); i++) {
            String querySql="SELECT * FROM tbl_data_query WHERE STATUS =0 AND page_parent_uuid='"+jtPage.getContent().get(i).get("uuid")+"'";
            String dataQueryStr= ApiDao.nullToStrFilter(this.getJdbcTemplate().queryForList(querySql));
            jtPage.getContent().get(i).put("query_data", JackJSON.parseObject(dataQueryStr, ArrayList.class));
            String formSql="SELECT * FROM tbl_data_form WHERE STATUS =0 AND page_parent_uuid='"+jtPage.getContent().get(i).get("uuid")+"'";
            String dataFormStr=ApiDao.nullToStrFilter(this.getJdbcTemplate().queryForList(formSql));
            jtPage.getContent().get(i).put("form_data", JackJSON.parseObject(dataFormStr, ArrayList.class));
        }
        return jtPage;
    }

    public void initBpmField(String tableName){
        List<Map<String,Object>> bpmFieldList= JackJSON.parseObject(String.valueOf(BaseConfigStaticCache.get(SYSTEM_SETTINGS_DS_BPM_FIELD_JSON)), ArrayList.class);
        for (int i = 0; i < bpmFieldList.size(); i++) {
            String fieldName=String.valueOf(bpmFieldList.get(i).get("field_name"));
            String sql="SHOW FULL COLUMNS FROM "+tableName+" where field='"+fieldName+"'";
            List<Map<String,Object>> fieldList=this.getJdbcTemplate().queryForList(sql);
            if(fieldList.size()>0){
                continue;
            }
            String type=String.valueOf(bpmFieldList.get(i).get("type"));
            String  alterSql="";
            if(!"null".equals(type)&&!type.equals("text")){//非text类型
                type+="("+bpmFieldList.get(i).get("length")+")";
                alterSql+= "ALTER TABLE `" + tableName + "` \n" + " ADD COLUMN `" + fieldName
                        + "` " + type + " NULL COMMENT '"+bpmFieldList.get(i).get("comment")+"'";
                this.getJdbcTemplate().execute(alterSql);
                action.dataVmTableAction.initFiled(tableName,fieldName);
            }else{//text类型
                alterSql+= "ALTER TABLE `" + tableName + "` \n" + " ADD COLUMN `" + fieldName
                        + "` " + type + " NULL COMMENT '"+bpmFieldList.get(i).get("comment")+"'";
                this.getJdbcTemplate().execute(alterSql);
                action.dataVmTableAction.initFiled(tableName,fieldName);
            }
        }
    }

    public JackJSONArray stepsSaveBefore(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JackJSONArray array) {
        for (int i = 0; i < array.size(); i++) {
            String id=String.valueOf(array.getJackJSONObject(i).get("id"));
            String dsCode=String.valueOf(array.getJackJSONObject(i).get("ds_code"));
            String dsTableName=String.valueOf(array.getJackJSONObject(i).get("ds_table_name"));
            String dsName=String.valueOf(array.getJackJSONObject(i).get("ds_name"));
            if("null".equals(id)||id.length()==0){
                String sql="SELECT COUNT(1) FROM tbl_data_source WHERE ds_code='"+dsCode+"'";
                Integer count=this.getJdbcTemplate().queryForObject(sql,Integer.class);
                if(count>0){
                    retJson.putAll(JackJSONObject.fromObject(action.apiService.getReturnDataByCode("6031")));
                    retJson.put("message",retJson.get("message")+" ds_code："+dsCode);
                    return new JackJSONArray();
                }
            }
            array.getJackJSONObject(i).remove("query_data");
            array.getJackJSONObject(i).remove("form_data");
            try {
                action.dataVmTableAction.initTable(dsTableName,dsName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return array;
    }
    public JackJSONArray stepsSaveAfter(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JackJSONArray array) {
        for (int i = 0; i < array.size(); i++) {
            String dsCode=String.valueOf(array.getJackJSONObject(i).get("ds_code"));
            Map<String,Object> dsMap=action.apiService.findDataSourceByCode(dsCode);
            String tableName=String.valueOf(dsMap.get("ds_table_name"));
            String dsName=String.valueOf(array.getJackJSONObject(i).get("ds_name"));
            String isAutoCreateField=String.valueOf(array.getJackJSONObject(i).get("is_auto_create_field"));
            String myselfFieldTag=String.valueOf(array.getJackJSONObject(i).get("myself_field_tag"));
            JackJSONArray fieldArray=new JackJSONArray();
            if(isAutoCreateField.equals("Y")){
                for (int j = 0; j < 5; j++) {
                    JackJSONObject fieldInfo=new JackJSONObject();
                    fieldInfo.put("id","");
                    fieldInfo.put("field","test_"+(j+1));
                    fieldInfo.put("type","varchar");
                    fieldInfo.put("comment","示例字段"+(j+1));
                    fieldInfo.put("length",255);
                    fieldInfo.put("default_value","");
                    fieldArray.add(fieldInfo);
                }
            }else{
                String[] arr = myselfFieldTag.split(",");
                for (int j = 0; j < arr.length; j++) {
                    String pinyin=ApiDao.chineseToPinyin(arr[j],"_");
                    if(!arr[j].equals("")&&!pinyin.equals("")){
                        JackJSONObject fieldInfo=new JackJSONObject();
                        fieldInfo.put("id","");
                        fieldInfo.put("field",ApiDao.chineseToPinyin(arr[j],"_"));
                        fieldInfo.put("type","varchar");
                        fieldInfo.put("comment",arr[j]);
                        fieldInfo.put("length",255);
                        fieldInfo.put("default_value","");
                        fieldArray.add(fieldInfo);
                    }
                }
            }
            for (int j = 0; j < fieldArray.size(); j++) {
                String id=String.valueOf(fieldArray.getJackJSONObject(j).get("id"));
                String fieldName=String.valueOf(fieldArray.getJackJSONObject(j).get("field"));
                String fieldType=String.valueOf(fieldArray.getJackJSONObject(j).get("type"));
                String fieldComment=String.valueOf(fieldArray.getJackJSONObject(j).get("comment"));
                String fieldLength=String.valueOf(fieldArray.getJackJSONObject(j).get("length"));
                String defaultValue=String.valueOf(fieldArray.getJackJSONObject(j).get("default_value"));
                String defaultSql="";
                if(DBCheck.isKingbase()){
                    if(!fieldType.equals("text")&&!fieldType.equals("TEXT")){
                        if(!"".equals(fieldLength)){
                            fieldType=fieldType+"("+fieldLength+")";
                        }else{
                            retJson.put("message","保存失败，原因是："+fieldName+" 字段未指定长度");
                            return new JackJSONArray();
                        }
                    }
                    String querySql="SELECT a.attnum,\n" +
                            "       a.attname AS column_name,\n" +
                            "       t.typname AS data_type,\n" +
                            "       CASE WHEN a.atttypmod<=0 THEN null ELSE (a.atttypmod-4) END AS lengthvar,\n" +
                            "       a.attnotnull AS notnull,\n" +
                            "       b.description AS comment\n" +
                            "  FROM sys_class c,\n" +
                            "       sys_attribute a\n" +
                            "       LEFT OUTER JOIN sys_description b ON a.attrelid=b.objoid AND a.attnum = b.objsubid,\n" +
                            "       sys_type t\n" +
                            " WHERE c.relname = '"+tableName+"'\n" +
                            "       and a.attnum > 0\n" +
                            "       and a.attrelid = c.oid\n" +
                            "       and a.atttypid = t.oid\n"+
                            "       and a.attname ='"+fieldName+"'"+
                            " ORDER BY a.attnum";
                    List<Map<String, Object>> colList=this.getJdbcTemplate().queryForList(querySql);
                    if(colList.size()>0){
                        //已存在字段
                        retJson.put("status","no_code");
                        retJson.put("message","保存失败，原因是："+fieldName+" 字段已存在");
                        return new JackJSONArray();
                    }
                    String sql="";
                    if(!"null".equals(id)&&id.length()>0){
                        sql += "ALTER TABLE " + tableName + " ALTER " + fieldName +
                                " TYPE " + fieldType ;
                    }else{
                        //ALTER TABLE myTest ADD COLUMN s_no varchar(512)
                        sql = "ALTER TABLE " + tableName + " " + "ADD COLUMN " + fieldName
                                + " "+fieldType;
                    }
                    this.getJdbcTemplate().execute(sql);
                    this.getJdbcTemplate().execute("comment on column "+tableName+"."+fieldName+" is '"+fieldComment+"'");
                }else{
                    if(!fieldType.equals("text")&&!fieldType.equals("longtext")){
                        if("".equals(fieldLength)){
                            retJson.put("message","保存失败，原因是："+fieldName+" 字段未指定长度");
                            return new JackJSONArray();
                        }
                        if(fieldType.equals("int")&&!defaultValue.equals("")){
                            defaultSql+=" DEFAULT '"+defaultValue+"'";
                        }else if(fieldType.equals("varchar")){
                            defaultSql+=" DEFAULT '"+defaultValue+"'";
                        }
                        fieldType=fieldType+"("+fieldLength+")";
                    }
                    String sql="";
                    String querySql="SHOW FULL COLUMNS FROM `"+tableName+"` WHERE FIELD='"+fieldName+"'";
                    List<Map<String, Object>> colList=this.getJdbcTemplate().queryForList(querySql);
                    if(colList.size()>0){
                        //已存在字段
                        retJson.put("status","no_code");
                        retJson.put("message","保存失败，原因是："+fieldName+" 字段已存在");
                        return new JackJSONArray();
                    }
                    if(!"null".equals(id)&&id.length()>0){
                        sql += "ALTER TABLE `" + tableName + "` \n" + "CHANGE COLUMN `" + fieldName + "` `" + fieldName
                                + "` " + fieldType + defaultSql+" COMMENT '"+fieldComment+"'";
                    }else{
                        sql = "ALTER TABLE `" + tableName + "` \n" + "ADD COLUMN `" + fieldName
                                + "` "+fieldType+defaultSql+" COMMENT '"+fieldComment+"'";
                    }
                    this.getJdbcTemplate().execute(sql);
                }
            }

            Map<String,Object> queryMap = new HashMap<>();
            String queryCode=String.valueOf(array.getJackJSONObject(i).get("query_code"));
            queryMap.put("page_parent_uuid",dsMap.get("uuid"));
            queryMap.put("query_code",queryCode);
            queryMap.put("query_name",dsName);
            queryMap.put("is_managing","Y");//默认展示管理列
            action.baseService.save("tbl_data_query",queryMap);
            initQueryFieldByDsSteps(String.valueOf(queryMap.get("uuid")));
            initButtonByDsSteps(String.valueOf(queryMap.get("uuid")));

            Map<String,Object> formMap = new HashMap<>();
            String formCode=String.valueOf(array.getJackJSONObject(i).get("form_code"));
            formMap.put("page_parent_uuid",dsMap.get("uuid"));
            formMap.put("form_code",formCode);
            formMap.put("form_name",dsName);
            formMap.put("layout_info","");
            action.baseService.save("tbl_data_form",formMap);
            initFormFieldByDsSteps(String.valueOf(formMap.get("uuid")));
            initButtonByDsSteps(String.valueOf(formMap.get("uuid")));

            Map<String,Object> pageMap = new HashMap<>();
            String pageCode=String.valueOf(array.getJackJSONObject(i).get("page_code"));
            pageMap.put("page_code",pageCode);
            pageMap.put("page_name",dsName);
            pageMap.put("layout_info","");
            action.baseService.save("tbl_data_page",pageMap);

            Map<String,Object> pageComponentMap = new HashMap<>();
            pageComponentMap.put("page_parent_uuid",pageMap.get("uuid"));
            pageComponentMap.put("component_type","dataSource");
            pageComponentMap.put("component_name",dsName);
            pageComponentMap.put("ds_code",dsCode);
            pageComponentMap.put("query_code",queryCode);
            pageComponentMap.put("form_code",formCode);
            action.baseService.save("tbl_data_page_component",pageComponentMap);

        }
        return array;
    }

    public Map<String,Object> initQueryFieldByDsSteps(String queryParentUUID){
        Map<String,Object> map=new HashMap<>();
        String queryTableNameSql="SELECT ds_table_name FROM tbl_data_source WHERE uuid=(SELECT page_parent_uuid FROM tbl_data_query WHERE status=0 and uuid='"+queryParentUUID+"')";
        String tableName=this.getJdbcTemplate().queryForObject(queryTableNameSql,String.class);
        List<Map<String,Object>> colInfoList= BaseDao.getAllCommentsByTableName(tableName, this.getJdbcTemplate());
        int isQueryNum=0;
        for(int i=0;i<colInfoList.size();i++) {
            String name=String.valueOf(colInfoList.get(i).get("Field"));
            String sql="select count(1) from tbl_data_query_info where status=0 and name='"+name+"' and page_parent_uuid='"+queryParentUUID+"'";
            Integer count=this.getJdbcTemplate().queryForObject(sql,Integer.class);
            if(count==0){
                Map<String,Object> viewMap= JackJSONObject.fromObject(BaseConfigStaticCache.get(SYSTEM_SETTINGS_DS_QUERY_JSON));
                if(colInfoList.get(i).get("Type").toString().indexOf("int")>=0) {
                    viewMap.put("type","long");
                }else {
                    viewMap.put("type","String");
                }
                if(name.equals("status")){
                    viewMap.put("default_value", "0");
                }
                DateTime d = new DateTime();
                viewMap.put("create_time", d.toString("yyyy-MM-dd HH:mm:ss"));
                viewMap.put("page_parent_uuid", queryParentUUID);
                viewMap.put("name",name);
                viewMap.put("label_name", String.valueOf(colInfoList.get(i).get("Comment")));
                String[] arr = {"id", "uuid", "page_parent_uuid", "status","create_user_id","create_org_id","create_org_name","create_user",
                        "create_time","create_date","update_user","update_time","update_date","user_area","data_source","form_version","is_history","cron_expression"};
                boolean found = Arrays.stream(arr).anyMatch(str -> str.contains(name));
                if(!found&&isQueryNum<2){//前两个字段设置文本框并查询
                    isQueryNum++;
                    viewMap.put("show_type","text");
                    viewMap.put("is_query","Y");
                }
                if(!found){//非系统字段设置列表显示并允许导出
                    viewMap.put("is_list","Y");
                    viewMap.put("is_export_excel","Y");
                }
                action.baseService.save("tbl_data_query_info",viewMap);
            }
        }
        map.put("message","同步成功");
        action.khcRedisCache.deleteAllQueryInfo();//清除缓存的表结构信息
        return map;
    }

    public Map<String,Object> initFormFieldByDsSteps(String formUUID){
        Map<String,Object> map=new HashMap<>();
        String queryTableNameSql="SELECT ds_table_name FROM tbl_data_source WHERE uuid=(SELECT page_parent_uuid FROM tbl_data_form WHERE status=0 and uuid='"+formUUID+"')";
        String tableName=this.getJdbcTemplate().queryForObject(queryTableNameSql,String.class);
        List<Map<String,Object>> colInfoList= BaseDao.getAllCommentsByTableName(tableName, this.getJdbcTemplate());
        for(int i=0;i<colInfoList.size();i++) {
            String name=String.valueOf(colInfoList.get(i).get("Field"));
            String sql="select count(1) from tbl_data_form_info where status=0 and name='"+name+"' and page_parent_uuid='"+formUUID+"'";
            Integer count=this.getJdbcTemplate().queryForObject(sql,Integer.class);
            if(count==0){
                Map<String,Object> viewMap= JackJSONObject.fromObject(BaseConfigStaticCache.get(SYSTEM_SETTINGS_DS_FORM_JSON));
                if(colInfoList.get(i).get("Type").toString().indexOf("int")>=0) {
                    viewMap.put("type","long");
                }else {
                    viewMap.put("type","String");
                }
                if(name.equals("status")){
                    viewMap.put("default_value", "0");
                }
                DateTime d = new DateTime();
                viewMap.put("create_time", d.toString("yyyy-MM-dd HH:mm:ss"));
                viewMap.put("page_parent_uuid", formUUID);
                viewMap.put("name",name);
                viewMap.put("label_name", String.valueOf(colInfoList.get(i).get("Comment")));
                String[] arr = {"id", "uuid", "page_parent_uuid", "status","create_user_id","create_org_id","create_org_name","create_user",
                        "create_time","create_date","update_user","update_time","update_date","user_area","data_source","form_version","is_history","cron_expression"};
                boolean found = Arrays.stream(arr).anyMatch(str -> str.contains(name));
                if(!found){
                    viewMap.put("show_type","text");
                }
                action.baseService.save("tbl_data_form_info",viewMap);
            }
        }
        map.put("message","同步成功");
        action.khcRedisCache.deleteAllFormInfo();//清除缓存的表结构信息
        return map;
    }

    public Map<String,Object> initButtonByDsSteps(String parentUUID){
        Map<String,Object> map=new HashMap<>();
        String sql="SELECT count(1) FROM tbl_data_button WHERE status=0 and page_parent_uuid='"+parentUUID+"'";
        String queryCountSql="select count(1) from tbl_data_query where uuid='"+parentUUID+"'";
        Integer queryCount=this.getJdbcTemplate().queryForObject(queryCountSql,Integer.class);
        if(queryCount>0){
            List<Map<String,Object>> list= JackJSON.parseObject(String.valueOf(BaseConfigStaticCache.get(SYSTEM_SETTINGS_DS_QUERY_BUTTON_JSON)), ArrayList.class);
            for (int i = 0; i < list.size(); i++) {
                Integer count=this.getJdbcTemplate().queryForObject(sql+" and button_method='"+list.get(i).get("button_method")+"'",Integer.class);
                if(count>0){
                    continue;
                }
                String uuid= UUID.randomUUID().toString().replaceAll("-","");
                list.get(i).put("uuid",uuid);
                list.get(i).put("page_parent_uuid",parentUUID);
                action.baseService.save("tbl_data_button", list.get(i));
                action.khcRedisCache.deleteAllButton();//清除缓存的按钮信息
            }
        }
        String formCountSql="select count(1) from tbl_data_form where uuid='"+parentUUID+"'";
        Integer formCount=this.getJdbcTemplate().queryForObject(formCountSql,Integer.class);
        if(formCount>0){
            List<Map<String,Object>> list= JackJSON.parseObject(String.valueOf(BaseConfigStaticCache.get(SYSTEM_SETTINGS_DS_FORM_BUTTON_JSON)), ArrayList.class);
            for (int i = 0; i < list.size(); i++) {
                Integer count=this.getJdbcTemplate().queryForObject(sql+" and button_method='"+list.get(i).get("button_method")+"'",Integer.class);
                if(count>0){
                    continue;
                }
                String uuid= UUID.randomUUID().toString().replaceAll("-","");
                list.get(i).put("uuid",uuid);
                list.get(i).put("page_parent_uuid",parentUUID);
                action.baseService.save("tbl_data_button", list.get(i));
                action.khcRedisCache.deleteAllButton();//清除缓存的按钮信息
            }
        }
        map.put("message","同步成功");
        return map;
    }
}
