package com.chenyang.nse.bussiness.controller.core;

import ch.qos.logback.classic.Logger;
import com.chenyang.nse.bussiness.annot.EncryptLog;
import com.chenyang.nse.bussiness.annot.PassToken;
import com.chenyang.nse.bussiness.commmon.json.ErrCode;
import com.chenyang.nse.bussiness.commmon.json.RespHelper;
import com.chenyang.nse.bussiness.commmon.json.Response;
import com.chenyang.nse.bussiness.config.PropertiesLoaderUtils;
import com.chenyang.nse.bussiness.controller.core.encryption.TCoreEncryptionController;
import com.chenyang.nse.bussiness.dao.core.key.TCoreKeyClientParamDao;
import com.chenyang.nse.bussiness.dao.table.base.TBaseAppUserDao;
import com.chenyang.nse.bussiness.dao.table.core.TCoreDatasystemDao;
import com.chenyang.nse.bussiness.dao.table.core.dataproject.TCoreSecretkeyDao;
import com.chenyang.nse.bussiness.dao.table.core.encryption.TCoreEncryptionDao;
import com.chenyang.nse.bussiness.dao.table.core.encryption.TCoreEncryptionTypeFieldDao;
import com.chenyang.nse.bussiness.entity.orm.table.core.ProxyJarFields;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystem;
import com.chenyang.nse.bussiness.entity.orm.table.core.TEncryptionProxyHost;
import com.chenyang.nse.bussiness.entity.orm.table.core.dataproject.TCoreDataProject;
import com.chenyang.nse.bussiness.entity.orm.table.core.dataproject.TCoreSecretkey;
import com.chenyang.nse.bussiness.entity.orm.table.core.encryption.ColumnPrimaryKeyInfo;
import com.chenyang.nse.bussiness.entity.orm.table.core.encryption.TCoreEncryption;
import com.chenyang.nse.bussiness.entity.orm.table.core.encryption.TCoreEncryptionTypeField;
import com.chenyang.nse.bussiness.entity.orm.table.core.key.TCoreKeyClientParam;
import com.chenyang.nse.bussiness.entity.vo.DataScopeEntity;
import com.chenyang.nse.bussiness.entity.vo.Scope;
import com.chenyang.nse.bussiness.entity.vo.encyption.EncryptionConfigVO;
import com.chenyang.nse.bussiness.entity.vo.excel.ExcelEncryptionVO;
import com.chenyang.nse.bussiness.entity.vo.strategy.ColumnInfoVO;
import com.chenyang.nse.bussiness.service.core.DataSecurityControlledAssetService;
import com.chenyang.nse.bussiness.service.core.DataSystemService;
import com.chenyang.nse.bussiness.service.core.TdataProjectService;
import com.chenyang.nse.bussiness.service.core.encryption.EncryptionConfigService;
import com.chenyang.nse.bussiness.service.core.encryption.EncryptionProxyService;
import com.chenyang.nse.bussiness.service.core.encryption.TCoreEncryptionService;
import com.chenyang.nse.bussiness.service.core.strategy.MaksingAppDataRuleService;
import com.chenyang.nse.bussiness.service.core.udf.UdfService;
import com.chenyang.nse.bussiness.tools.dataprocess.EncTaskTracker;
import com.chenyang.nse.bussiness.tools.dataprocess.EncryptProcessUtil;
import com.chenyang.nse.bussiness.tools.encryption.EncUtils;
import com.chenyang.nse.bussiness.tools.encryption.SM4Util;
import com.chenyang.nse.bussiness.tools.excel.ExcelValidation;
import com.chenyang.nse.bussiness.tools.filesystem.JarUtilTool;
import com.chenyang.nse.bussiness.tools.io.FileTool;
import com.chenyang.nse.bussiness.tools.jdbc.JdbcTool;
import com.chenyang.nse.bussiness.tools.logger.LoggerBuilder;
import com.chenyang.nse.bussiness.tools.msg.MesUtil;
import com.chenyang.nse.bussiness.tools.propertyutil.PropertyGhcaUtil;
import com.chenyang.nse.bussiness.tools.strategy.StrategyData;
import com.chenyang.nse.bussiness.tools.token.TokenUtil;
import com.chenyang.nse.bussiness.tools.zip.ZipUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({"/core/encryptionconfig"})
public class EncryptionConfigController {
   @Autowired
   EncryptionConfigService encryptionConfigService;
   @Autowired
   StrategyData strategyData;
   @Autowired
   DataSystemService dataSystemService;
   @Autowired
   TCoreDatasystemDao tCoreDatasystemDao;
   @Autowired
   @Qualifier("TCoreEncryptionContext")
   TCoreEncryptionService tCoreEncryptionService;
   @Autowired
   TCoreEncryptionController tCoreEncryptionController;
   @Autowired
   private TBaseAppUserDao tBaseAppUserDao;
   @Autowired
   EncryptionProxyService encryptionProxyService;
   @Autowired
   TCoreEncryptionTypeFieldDao TCoreEncryptionTypeFieldDao;
   @Autowired
   TCoreKeyClientParamDao tCoreKeyClientParamDao;
   @Autowired
   TCoreEncryptionDao tCoreEncryptionDao;
   @Autowired
   TCoreSecretkeyDao tCoreSecretkeyDao;
   @Autowired
   MaksingAppDataRuleService maksingAppDataRuleService;
   @Autowired
   DataSecurityControlledAssetService dataSecurityControlledAssetService;
   @Autowired
   UdfService udfService;
   @Autowired
   private TdataProjectService tdataProjectService;
   @Value("${classify.classifyEnable}")
   private boolean classifyEnable;
   @Value("${server.port}")
   private String port;
   public static final String EXPORT = "有缺少缺少主键的表存在无法导出,请前往设置";
   final String JAR_CONFIG_PROPERTIES = "gatewayconfig/config.properties";

   @EncryptLog
   @ResponseBody
   @RequestMapping({"/decrypt"})
   public Response<EncryptionConfigVO> getDecryptTable(@RequestBody EncryptionConfigVO vo) {
      EncryptionConfigVO encryptionConfigVO;
      try {
         if (StringUtils.isEmpty(vo.getSql())) {
            return RespHelper.<EncryptionConfigVO>createResp(false, "POP_00022", "请输入sql语句");
         }

         encryptionConfigVO = this.encryptionConfigService.decrypt(vo);
      } catch (Exception e) {
         StringWriter sw = new StringWriter();
         PrintWriter pw = new PrintWriter(sw);
         e.printStackTrace(pw);
         String content = sw.toString();
         return RespHelper.<EncryptionConfigVO>createResp(false, "POP_00022", MesUtil.getMsg("DIS_ERR_02", new String[]{"执行了非法的语句（此处只做数据查询用）"}));
      }

      return RespHelper.<EncryptionConfigVO>successResp(encryptionConfigVO);
   }

   @EncryptLog
   @ResponseBody
   @RequestMapping({"/save"})
   public Response<String> save(@RequestBody Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) {
      String dataareaid = (String)map.get("dataareaid");
      String dataareaname = (String)map.get("dataareaname");
      String projectid = (String)map.get("projectId");
      String dataSystemid = (String)map.get("datasystemid");
      String username = TokenUtil.getUserId(request.getHeader("token"));
      ((Map)map.get("map")).forEach((k, v) -> {
         String[] split = k.toString().split("#\\|#");
         String schemaname = split[0];
         String tablename = split[1];
         String fieldname = split[2];
         List<String> dataEncryptionTypeTidList = new ArrayList();
         List<String> dataColumList = new ArrayList();
         dataColumList.add(dataSystemid);
         dataColumList.add(fieldname);
         dataColumList.add(tablename);
         dataColumList.add(schemaname);
         String describe_info = (String)((Map)v).get("describe_info");
         String flag = (String)((Map)v).get("flag");
         String columnType = (String)((Map)v).get("columnType");
         String columnSize = (String)((Map)v).get("columnSize");
         String note = (String)((Map)v).get("note");
         String isLike = (String)((Map)v).get("isLike");
         String keepfirst = (String)((Map)v).get("keepfirst");
         String encdigit = (String)((Map)v).get("encdigit");
         String realitycolumnsize = (String)((Map)v).get("realitycolumnsize");
         String twoindex = (String)((Map)v).get("twoindex");
         String encryptionTypeId = (String)((Map)v).get("encryptionSecretKeyId");
         dataColumList.add(describe_info);
         dataColumList.add(flag);
         dataColumList.add(projectid);
         dataColumList.add(username);
         dataColumList.add(dataareaid);
         dataColumList.add(dataareaname);
         dataColumList.add(columnType);
         dataColumList.add(columnSize);
         dataColumList.add(note);
         dataColumList.add(isLike);
         dataColumList.add(keepfirst);
         dataColumList.add(encdigit);
         dataColumList.add(realitycolumnsize);
         dataColumList.add(twoindex);
         dataColumList.add(encryptionTypeId);
         dataEncryptionTypeTidList.add(encryptionTypeId);

         try {
            this.encryptionConfigService.saveColumnType(dataColumList, dataEncryptionTypeTidList);
         } catch (Exception e) {
            e.printStackTrace();
         }

         this.changeColumnLength(dataColumList);
      });
      this.encryptionProxyService.noticeProxyFetchEngineAndMaskingInfosByProject(projectid);
      return RespHelper.<String>successResp();
   }

   @EncryptLog
   @ResponseBody
   @RequestMapping({"/saveKafka"})
   public Response<String> saveKafka(@RequestBody Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) {
      String projectid = (String)map.get("projectId");
      String dataSystemid = (String)map.get("datasystemid");
      String username = TokenUtil.getUserId(request.getHeader("token"));
      String topic = (String)map.get("topic");
      String fileid = TokenUtil.getUserId(request.getHeader("fileid"));
      String encryptionSecretKeyId = TokenUtil.getUserId(request.getHeader("encryptionSecretKeyId"));
      List<String> dataColumList = new ArrayList();
      dataColumList.add(topic);
      dataColumList.add(fileid);
      dataColumList.add(projectid);
      dataColumList.add(dataSystemid);
      dataColumList.add(username);
      dataColumList.add(encryptionSecretKeyId);
      this.encryptionConfigService.saveKafka(dataColumList);
      return RespHelper.<String>successResp();
   }

   @ResponseBody
   @RequestMapping({"/queryKafkaEncryptionFileList"})
   public Response<List<Map<String, String>>> queryKafkaEncryptionFileList(@RequestBody EncryptionConfigVO vo) {
      List<Map<String, String>> list = new ArrayList();

      try {
         list = this.encryptionConfigService.queryEncryptionList(vo);
      } catch (Exception e) {
         e.printStackTrace();
      }

      return RespHelper.<List<Map<String, String>>>successResp(list);
   }

   private void changeColumnLength(List<String> dataColumnList) {
      try {
         String encKeyId = (String)dataColumnList.get(18);
         Properties props = PropertiesLoaderUtils.loadAllProperties("config.properties");
         if ("0".equals(props.getProperty("is_encrypted"))) {
            TCoreDatasystem tCoreDatasystem = (TCoreDatasystem)this.tCoreDatasystemDao.queryUnique(new Criterion[]{Restrictions.eq("id", dataColumnList.get(0))});
            Connection connection = JdbcTool.getConnection(tCoreDatasystem);
            String loggerPath = System.getProperty("user.dir") + File.separator + "encryprocesslog" + File.separator + (String)dataColumnList.get(6) + File.separator + (String)dataColumnList.get(0);
            Logger encryptionlogger = (new LoggerBuilder()).getLogger(loggerPath, (String)dataColumnList.get(3) + "." + (String)dataColumnList.get(2));
            EncryptionConfigVO vo = new EncryptionConfigVO();
            vo.setDatasystem_id((String)dataColumnList.get(0));
            vo.setSchema((String)dataColumnList.get(3));
            vo.setTable_name((String)dataColumnList.get(2));
            vo.setProjectid((String)dataColumnList.get(6));
            List<ColumnInfoVO> columnInfoList = new ArrayList();
            List<com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO> allColumnList = this.encryptionConfigService.queryOriginalList(vo);

            for(int i = 0; i < allColumnList.size(); ++i) {
               if (dataColumnList.contains(((com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO)allColumnList.get(i)).getColumnname())) {
                  ColumnInfoVO cv = new ColumnInfoVO();
                  cv.setColumnName((String)dataColumnList.get(1));
                  cv.setColumnType((String)dataColumnList.get(10));
                  cv.setColumnSize((String)dataColumnList.get(11));
                  cv.setIsLike((String)dataColumnList.get(13));
                  cv.setKeepfirst((String)dataColumnList.get(14));
                  cv.setEncdigit((String)dataColumnList.get(15));
                  cv.setRealitycolumnsize((String)dataColumnList.get(16));
                  cv.setTwoindex((String)dataColumnList.get(17));
                  if (StringUtils.isNotBlank(encKeyId)) {
                     Map<String, String> encryptionInfo = this.tCoreEncryptionService.queryEncryptionInfo(encKeyId);
                     cv.setEncryptionType((String)encryptionInfo.get("encryptionType"));
                  }

                  columnInfoList.add(cv);
               }
            }

            if (StringUtils.isNotBlank(encKeyId)) {
               EncryptProcessUtil.addAllColumnLength(connection, encryptionlogger, tCoreDatasystem, columnInfoList, (String)dataColumnList.get(3), (String)dataColumnList.get(2), allColumnList);
            } else {
               EncryptProcessUtil.rollbackAllColumnLength(connection, encryptionlogger, tCoreDatasystem, columnInfoList, (String)dataColumnList.get(3), (String)dataColumnList.get(2));
            }

            connection.close();
         }
      } catch (Exception e) {
         e.printStackTrace();
      }

   }

   @PassToken
   @ResponseBody
   @RequestMapping({"/queryOriginalList"})
   public Response queryList(@RequestBody EncryptionConfigVO vo) {
      String datasystemid = vo.getDatasystem_id();
      String schema = vo.getSchema();
      String tablename = vo.getTable_name();
      List<com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO> list = new ArrayList();

      try {
         List<com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO> var13 = this.encryptionConfigService.queryOriginalList(vo);
         list = (List)var13.stream().filter((c) -> !c.getColumnname().endsWith(PropertyGhcaUtil.digestSuffix)).collect(Collectors.toList());
         TCoreDatasystem tCoreDatasystem = this.maksingAppDataRuleService.queryDataSystemById(datasystemid);
         Map<String, String> map = new HashMap();
         map.put("dbip", tCoreDatasystem.getDbip());
         map.put("dbport", tCoreDatasystem.getDbport());
         map.put("dbtype", tCoreDatasystem.getDbtype());
         List<Map<String, String>> maplist = new ArrayList();
         maplist.add(map);
         if (this.classifyEnable) {
            for(com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO columnInfoVO : list) {
               Map<String, List<DataScopeEntity>> classifyInfos = this.dataSecurityControlledAssetService.getClassifyInfos(maplist, schema, tablename);
               this.mergeClassify(classifyInfos, columnInfoVO);
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }

      return RespHelper.successResp(list);
   }

   public void mergeClassify(Map<String, List<DataScopeEntity>> classifyInfos, com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO columnInfoVO) {
      List<DataScopeEntity> dataAreaList = (List)classifyInfos.get("dataareas");
      if (null != dataAreaList && dataAreaList.size() > 0) {
         List<DataScopeEntity> collect = (List)dataAreaList.stream().filter((x) -> x.getColumnName().equals(columnInfoVO.getColumnname())).collect(Collectors.toList());
         if (null != collect && collect.size() > 0) {
            columnInfoVO.setDataareaName(((DataScopeEntity)collect.get(0)).getDataareaName());
         }
      }

      List<DataScopeEntity> scopeNameList = (List)classifyInfos.get("scopeNames");
      Set<Scope> scopeList = new HashSet();
      if (null != scopeNameList && scopeNameList.size() > 0) {
         List<DataScopeEntity> collect = (List)scopeNameList.stream().filter((x) -> x.getColumnName().equals(columnInfoVO.getColumnname())).collect(Collectors.toList());
         if (null != collect && collect.size() > 0) {
            for(DataScopeEntity scopeEntity : collect) {
               Scope scope = new Scope();
               scope.setScopeName(scopeEntity.getScopeName());
               scope.setIsAuto(scopeEntity.getIsAuto());
               scopeList.add(scope);
            }

            columnInfoVO.setScopes((List)scopeList.stream().collect(Collectors.toList()));
         }
      }

      List<DataScopeEntity> fieldSensitivesList = (List)classifyInfos.get("fieldSensitives");
      if (null != fieldSensitivesList && fieldSensitivesList.size() > 0) {
         List<DataScopeEntity> collect = (List)fieldSensitivesList.stream().filter((x) -> x.getColumnName().equals(columnInfoVO.getColumnname())).collect(Collectors.toList());
         if (null != collect && collect.size() > 0) {
            columnInfoVO.setSensitiveLevel(((DataScopeEntity)collect.get(0)).getSensitiveLevel());
         }
      }

   }

   @ResponseBody
   @RequestMapping({"/queryEncryptionList"})
   public Response<List<Map<String, String>>> queryEncryptionList(@RequestBody EncryptionConfigVO vo) {
      List<Map<String, String>> list = new ArrayList();

      try {
         list = this.encryptionConfigService.queryEncryptionList(vo);
      } catch (Exception e) {
         e.printStackTrace();
      }

      return RespHelper.<List<Map<String, String>>>successResp(list);
   }

   @ResponseBody
   @RequestMapping({"/queryDatasystemInfo"})
   public Response queryDatasystemInfo(@RequestBody Map<String, String> map) {
      String dataSystemId = (String)map.get("dataSystemId");
      String projectId = (String)map.get("projectId");
      Map<String, Object> result = this.encryptionConfigService.queryDatasystemInfo(dataSystemId, projectId);
      return RespHelper.successResp(result);
   }

   @ResponseBody
   @RequestMapping({"/querytableInfo"})
   public Response querytableInfo(@RequestBody Map<String, String> map) {
      String dataSystemId = (String)map.get("dataSystemId");
      String projectId = (String)map.get("projectId");
      String tableName = (String)map.get("tableName");
      String schema = (String)map.get("schema");
      Map<String, Object> result = this.encryptionConfigService.querytableInfo(dataSystemId, projectId, schema, tableName);
      return RespHelper.successResp(result);
   }

   @PassToken
   @GetMapping({"/download"})
   @ResponseBody
   public void downloadByBatchJar(@RequestParam("appProjectName") String appProjectName, @RequestParam("projectid") String projectid, @RequestParam("gatewayUrl") String gatewayUrl, @RequestParam("gatewayPort") String gatewayPort, @RequestParam("appUrl") String appUrl, @RequestParam("appPort") String appPort, HttpServletRequest request, HttpServletResponse response) throws Exception {
      Properties props = new Properties();

      try {
         props = PropertiesLoaderUtils.loadAllProperties("config.properties");
      } catch (IOException e) {
         e.printStackTrace();
      }

      TCoreDataProject project = this.tdataProjectService.selectOneDataProject(projectid);
      if (project.getProjectType().equals("udf")) {
         this.udfService.download(response, gatewayPort);
      } else {
         if (StringUtils.isBlank(gatewayPort)) {
            gatewayPort = this.port;
         }

         String filepath = props.getProperty("jdbcproxypath");
         File fileTarget = new File(filepath);
         if (!fileTarget.exists()) {
            fileTarget.mkdirs();
         }

         this.strategyData.getDesensitizationStrategy(projectid, "1");
         Map<String, byte[]> fileInJarMap = new HashMap();
         StringBuilder configContent = new StringBuilder();
         String dataSynchronousMode = !appUrl.equals("''") && !appPort.equals("''") ? "push" : "pull";
         if ("push".equals(dataSynchronousMode)) {
            String appUrlInDB = appUrl.contains("http") ? appUrl + ":" + appPort : "http://" + appUrl + ":" + appPort;
            List<TEncryptionProxyHost> proxyHosts = this.tBaseAppUserDao.getProxyHosts(projectid, appUrlInDB);
            if (proxyHosts != null && proxyHosts.size() > 0) {
               for(TEncryptionProxyHost proxy : proxyHosts) {
                  proxy.setHost_url(appUrlInDB);
                  proxy.setProject_id(projectid);
                  this.tBaseAppUserDao.updateProxyHosts(proxy);
               }
            } else {
               this.tBaseAppUserDao.saveProxyHosts(projectid, appUrl + ":" + appPort);
            }

            this.tBaseAppUserDao.saveProxyJarInfo(appUrl, appPort, gatewayUrl, gatewayPort, projectid, appProjectName);
         }

         try {
            String var38 = gatewayUrl.contains("http") ? gatewayUrl : "http://" + gatewayUrl;
            gatewayUrl = var38 + ":" + gatewayPort;
            configContent.append("#网关地址");
            configContent.append("\r\n");
            configContent.append("gatewayurl=" + gatewayUrl);
            configContent.append("\r\n");
            if ("push".equals(dataSynchronousMode)) {
               configContent.append("#第三方应用端口");
               configContent.append("\r\n");
               configContent.append("socketport=" + appPort);
               configContent.append("\r\n");
            }

            configContent.append("#插件对应的网关项目的projectId");
            configContent.append("\r\n");
            configContent.append("projectid=" + projectid);
            configContent.append("\r\n");
            configContent.append("#插件同步数据的方式（推/拉）");
            configContent.append("\r\n");
            configContent.append("dataSynchronousMode=" + dataSynchronousMode);
            configContent.append("\r\n");
            configContent.append("#轮询时间(默认1分钟)");
            configContent.append("\r\n");
            configContent.append("pullInterval=60000");
            configContent.append("\r\n");
            configContent.append("#是否记录本地同步日志");
            configContent.append("\r\n");
            configContent.append("isSave=false");
            configContent.append("\r\n");
            configContent.append("#加密标识");
            configContent.append("\r\n");
            configContent.append("encryption.label=" + props.getProperty("encryption.label"));
            configContent.append("\r\n");
            configContent.append("#单个字符加密后连接起来用某个字符进行分割");
            configContent.append("\r\n");
            configContent.append("encryption.like.split=#");
            configContent.append("\r\n");
            configContent.append("##like是否执行按照单个字符进行加密开关。1表示按照单个字符进行加密。0表示按照字符串整体进行加密, 默认不开启");
            configContent.append("\r\n");
            configContent.append("encryption.like.open=1");
            configContent.append("\r\n");
            TCoreKeyClientParam tCoreKeyClientParam = (TCoreKeyClientParam)this.tCoreKeyClientParamDao.queryUnique(new Criterion[]{Restrictions.eq("projectid", projectid)});
            String remoteFlag = "0";
            if (Objects.nonNull(tCoreKeyClientParam) && Objects.equals(tCoreKeyClientParam.getEncdeclocation(), "1")) {
               remoteFlag = "1";
            }

            configContent.append("#is remote enc/dec");
            configContent.append("\r\n");
            configContent.append("encryption.remote=" + remoteFlag);
            configContent.append("\r\n");
            configContent.append("#是否采用远程加密卡加解密，false不使用加密卡，true使用加密卡，encryption.remote=1表示远程加解密");
            configContent.append("\r\n");
            configContent.append("ccoresdf=false");
            configContent.append("\r\n");
            configContent.append("mode=CCORESDF");
            configContent.append("\r\n");
            String cacheFlag = "1";
            if (Objects.nonNull(tCoreKeyClientParam) && Objects.equals(tCoreKeyClientParam.getKeylocation(), "2")) {
               cacheFlag = "2";
            }

            configContent.append("#key location cache or (cache and file)");
            configContent.append("\r\n");
            configContent.append("encryption.keyCache=" + cacheFlag);
            configContent.append("\r\n");
            configContent.append("#插件集成的项目启动后，向平台时注册自己的端口号标识");
            configContent.append("\r\n");
            configContent.append("rootport=54321");
            configContent.append("\r\n");
            configContent.append("#秘钥存放位置");
            configContent.append("\r\n");
            configContent.append("encryption.location=/home/ghca/data/encryption.properties");
            configContent.append("\r\n");
            configContent.append("#完整性规则存放位置");
            configContent.append("\r\n");
            configContent.append("digest.location=/home/ghca/data/digest.properties");
            configContent.append("\r\n");
            configContent.append("#外部配置文件信息地址");
            configContent.append("\r\n");
            configContent.append("encryption.config.location=/home/ghca/data/plugin/config.properties");
            configContent.append("\r\n");
            configContent.append("#驱动列表，如有多个以#分割");
            configContent.append("\r\n");
            configContent.append("encryption.drivers=");
            configContent.append("\r\n");
            configContent.append("#插件是否打印日志,如果为空或者为0不打印日志信息，1为打印日志信息");
            configContent.append("\r\n");
            configContent.append("encryption.log=0");
            configContent.append("\r\n");
            configContent.append("\r\n");
            configContent.append("#插件是否开启sql查询时where条件like替换功能，1为开启，0为不开启");
            configContent.append("\r\n");
            configContent.append("replaceSql=0");
            configContent.append("\r\n");
            configContent.append("#是否根据登录账号开启脱敏功能，1为开启，0为未开启");
            configContent.append("\r\n");
            configContent.append("maskingRule=0");
            configContent.append("\r\n");
            configContent.append("\r\n");
            configContent.append("#密文分隔符");
            configContent.append("\r\n");
            configContent.append("encryption.separator=" + (props.getProperty("encryption.label.suffix") != null ? props.getProperty("encryption.label.suffix").trim() : ""));
            configContent.append("\r\n");
            configContent.append("\r\n");
            configContent.append("#******************************** 规则配置信息 ***********************************");
            configContent.append("\r\n");
            configContent.append("#localfile/gateway");
            configContent.append("\r\n");
            configContent.append("encryption.rule-origin=gateway");
            configContent.append("\r\n");
            configContent.append("#localfile/gateway");
            configContent.append("\r\n");
            configContent.append("masking.rule-origin=gateway");
            configContent.append("\r\n");
            configContent.append("#reload config");
            configContent.append("\r\n");
            configContent.append("rule.load-period=30");
            configContent.append("\r\n");
            configContent.append("#gateway config");
            configContent.append("\r\n");
            configContent.append("gateway.protocol=http"); // 这里和下面第二行暂时改成 http
            configContent.append("\r\n");
            configContent.append("gateway.host=" + gatewayUrl.replace("http://", "").replace(":", "").replace(gatewayPort, ""));
            configContent.append("\r\n");
            configContent.append("gateway.port=" + gatewayPort);
            configContent.append("\r\n");
            configContent.append("#0:ry系统，1：masking 系统");
            configContent.append("\r\n");
            configContent.append("getUserType=0");
            fileInJarMap.put("gatewayconfig/config.properties", configContent.toString().getBytes(StandardCharsets.UTF_8));
            JarUtilTool.writeJarFileBatch(filepath, fileInJarMap);
         } catch (Exception e) {
            e.printStackTrace();
         }

         String odbcFilePath = props.getProperty("odbcproxypath");
         Map<String, byte[]> odbcMap = new HashMap();
         StringBuilder odbcContent = new StringBuilder();

         try {
            gatewayUrl = gatewayUrl.contains("http") ? gatewayUrl : "http://" + gatewayUrl;
            odbcContent.append("[encryption]");
            odbcContent.append("\r\n");
            odbcContent.append("access_ip=127.0.0.1");
            odbcContent.append("\r\n");
            odbcContent.append("access_port=5009");
            odbcContent.append("\r\n");
            odbcContent.append("gateway_ip=" + gatewayUrl);
            odbcContent.append("\r\n");
            odbcContent.append("gateway_port=8020");
            odbcContent.append("\r\n");
            odbcContent.append("[odbc]");
            odbcContent.append("\r\n");
            odbcContent.append("driver=/home/ghca/setup/ora12/instantclient_12_1/libsqora.so.12.1");
            odbcContent.append("\r\n");
            odbcContent.append("win_driver=C:\\masking_odbc\\dll\\sqora32.dll");
            odbcMap.put("masking_odbc/config.ini", odbcContent.toString().getBytes(StandardCharsets.UTF_8));
            JarUtilTool.writeZipFileBatch(odbcFilePath, odbcMap);
         } catch (Exception e) {
            e.getMessage();
         }

         String path = "";
         OutputStream os = null;
         InputStream inputStream = null;
         String zipName = null;

         try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=plugins.zip");
            filepath = filepath.replace("encryption-proxy.jar", "");
            String encryption = filepath.replace("encryption/", "");
            zipName = encryption + "encryption_plugins.zip";
            ZipUtils.zip(zipName, filepath);
            inputStream = new BufferedInputStream(new FileInputStream(zipName));
            os = response.getOutputStream();
            byte[] b = new byte[2048];

            int length;
            while((length = inputStream.read(b)) > 0) {
               os.write(b, 0, length);
            }
         } catch (Exception e) {
            e.printStackTrace();
         } finally {
            os.close();
            inputStream.close();
            if (StringUtils.isNotEmpty(zipName)) {
               FileTool.removeFile(zipName);
            }

         }

      }
   }

   @PostMapping({"/showProxyInfo"})
   @ResponseBody
   @PassToken
   public Response showProxyInfo(@RequestBody Map<String, String> param) {
      new HashMap();
      List<ProxyJarFields> jarInfos = this.tBaseAppUserDao.getProxyJarInfo((String)param.get("projectId"), "", "");
      return RespHelper.successResp(jarInfos);
   }

   @PostMapping({"/saveProxyJarInfo"})
   @ResponseBody
   @PassToken
   public Response saveProxyJarInfo(@RequestBody Map<String, Object> param) {
      String gatewayUrl = (String)param.get("gatewayUrl");
      String gatewayPort = (String)param.get("gatewayPort");
      String projectId = (String)param.get("projectId");
      List<Map<String, String>> apps = (List)param.get("apps");
      this.tBaseAppUserDao.deleteProxyJarInfosBatchByProjectId(projectId);
      if (apps != null && apps.size() > 0) {
         for(Map<String, String> app : apps) {
            this.tBaseAppUserDao.saveProxyJarInfo((String)app.get("appUrl"), String.valueOf(app.get("appPort")), gatewayUrl, gatewayPort, projectId, (String)app.get("appProjectName"));
         }
      }

      return RespHelper.successResp();
   }

   @PostMapping({"/saveColumnPrimaryKey"})
   @ResponseBody
   public Response saveColumnPrimaryKey(@RequestBody ColumnPrimaryKeyInfo columnPrimaryKeyInfo) {
      this.encryptionConfigService.saveColumnPrimaryKey(columnPrimaryKeyInfo);
      return RespHelper.successResp();
   }

   @EncryptLog
   @ResponseBody
   @RequestMapping({"/exportToExcel"})
   public Response exportToExcel(@RequestBody ExcelEncryptionVO param, HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
      List<Map<String, Object>> dataList = this.encryptionConfigService.getAllColumnsByMap(param);
      Map<String, List<String>> data = this.encryptionConfigService.getKeyMap();
      String[] headers = new String[]{"工程名", "数据源id", "数据源", "schema", "表名", "字段名", "字段类型", "字段长度", "注释", "描述", "状态", "加密类型", "加密秘钥"};
      if (dataList.size() < 65536) {
         this.xls(param.getProject().getProject(), dataList, data, headers, request, response);
         return null;
      } else {
         return RespHelper.successResp("数据量太大暂不支持");
      }
   }

   @PostMapping({"/checkEncryptExcel"})
   @ResponseBody
   public Response checkEncryptExcel(@RequestBody ExcelEncryptionVO param) {
      String projectid = param.getProject().getId();
      Map<String, List> dataMap = this.encryptionConfigService.getProjectEncryptConfig(projectid);

      List<Map<String, String>> listNew = (List)dataMap.get("field");
      for(Map<String, String> map : listNew) {
         String flag = (String)map.get("flag");
         if (!"0".equals(flag) && !"5".equals(flag) && !"7".equals(flag) && (!StringUtils.isBlank((String)map.get("encryption_secretkey_id")) || !StringUtils.isBlank((String)map.get("encryptiontypename")) || !StringUtils.isBlank((String)map.get("secretkeyname")))) {
            return RespHelper.errResp(ErrCode.CANNOT_EXPORT_EXCEL);
         }
      }

      Properties props = new Properties();

      try {
         props = PropertiesLoaderUtils.loadAllProperties("config.properties");
      } catch (IOException e) {
         e.printStackTrace();
      }

      Map map = new HashMap();
      if ("0".equals(props.getProperty("is_enc_backupfile"))) {
         map.put("filetype", "xls");
      } else if ("1".equals(props.getProperty("is_enc_backupfile"))) {
         map.put("filetype", "txt");
      }

      return RespHelper.successResp(map);
   }

   @EncryptLog
   @ResponseBody
   @RequestMapping({"/getEncryptExcel"})
   public Response exportEncryptToExcel(@RequestBody ExcelEncryptionVO param, HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
      String projectid = param.getProject().getId();
      Properties props = new Properties();

      try {
         props = PropertiesLoaderUtils.loadAllProperties("config.properties");
      } catch (IOException e) {
         e.printStackTrace();
      }

      if ("0".equals(props.getProperty("is_enc_backupfile"))) {
         Map<String, List> dataMap = this.encryptionConfigService.getProjectEncryptConfig(projectid);
         this.encxls(param.getProject().getProject(), dataMap, request, response);
      } else if ("1".equals(props.getProperty("is_enc_backupfile"))) {
         Map<String, List> dataMap = this.encryptionConfigService.getProjectEncryptConfigTxt(projectid);
         this.enctxt(param.getProject().getProject(), dataMap, request, response);
      }

      return null;
   }

   private void xls(String name, List<Map<String, Object>> dataList, Map<String, List<String>> data, String[] headers, HttpServletRequest request, HttpServletResponse response) {
      Date date = new Date();
      String sdate = (new SimpleDateFormat("yyyyMMdd")).format(date);
      String fileName = name + "_" + sdate + ".xls";
      HSSFWorkbook workbook = new HSSFWorkbook();
      HSSFSheet sheet = null;

      try {
         sheet = workbook.createSheet("加密保存模板");
         HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);
         HSSFCellStyle style = this.getStyle(workbook);
         int columnNum = headers.length;
         HSSFRow headLine = sheet.createRow(0);
         sheet.setDefaultColumnWidth(15);
         sheet.setColumnWidth(0, 0);
         sheet.setColumnWidth(1, 0);

         for(int n = 0; n < columnNum; ++n) {
            HSSFCell cellRowName = headLine.createCell(n);
            cellRowName.setCellType(1);
            HSSFRichTextString text = new HSSFRichTextString(headers[n]);
            cellRowName.setCellValue(text);
            cellRowName.setCellStyle(columnTopStyle);
         }

         if (dataList.size() != 0) {
            HSSFCellStyle lockstyle = this.getStyle(workbook);
            lockstyle.setAlignment((short)2);
            lockstyle.setVerticalAlignment((short)1);
            ExcelValidation.addValidationToSheetV1(workbook, sheet, data, 'L', 'M', 1, dataList.size());
            lockstyle.setLocked(true);
            HSSFCellStyle unlockStyle = this.getStyle(workbook);
            unlockStyle.setLocked(false);
            unlockStyle.setLocked(false);
            HSSFRow dataRow = null;
            int index = 0;

            for(Map<String, Object> mapx : dataList) {
               ++index;
               dataRow = sheet.createRow(index);
               String dataType = "";

               for(int i = 0; i < headers.length; ++i) {
                  HSSFCell cell = dataRow.createCell(i);
                  String value = (String)mapx.get(headers[i]);
                  cell.setCellValue(value);
                  cell.setCellStyle(style);
                  if ("描述".equals(headers[i])) {
                     cell.setCellStyle(unlockStyle);
                     cell.setCellValue(StringUtils.isEmpty(value) ? "可修改" : value);
                  }

                  if ("待定".equals(value)) {
                     cell.setCellStyle(unlockStyle);
                     cell.setCellValue("可修改");
                  }

                  if ("字段类型".equals(headers[i])) {
                     dataType = value;
                  }

                  if (("加密类型".equals(headers[i]) || "加密秘钥".equals(headers[i])) && !"VARCHAR".equalsIgnoreCase(dataType) && !"VARCHAR2".equalsIgnoreCase(dataType) && !"CHAR".equalsIgnoreCase(dataType)) {
                     cell.setCellStyle(lockstyle);
                     cell.setCellValue("不可修改");
                  }
               }
            }

            sheet.protectSheet("123456");
         }

         try {
            this.getExportedField(workbook, fileName, response);
         } catch (Exception e) {
            e.printStackTrace();
         }
      } catch (Exception e) {
         e.printStackTrace();
      }

   }

   public void encxls(String projectname, Map<String, List> data, HttpServletRequest request, HttpServletResponse response) {
      Date date = new Date();
      String sdate = (new SimpleDateFormat("yyyyMMdd")).format(date);
      String fileName = projectname + "_encrule_backup_" + sdate + ".xls";
      HSSFWorkbook workbook = new HSSFWorkbook();
      String[] headers1 = new String[]{"id", "createtime", "createuser", "flag", "note", "updatetime", "updateuser", "encryption_name", "encryption_type"};

      try {
         List<Map<String, String>> encryptionList = (List)data.get("enc");
         this.generateSheet(workbook, "加密规则表", headers1, encryptionList);
         List<Map<String, String>> secretKeyList = (List)data.get("key");
         String[] headers2 = new String[]{"id", "createtime", "createuser", "flag", "note", "updatetime", "updateuser", "privatekey", "publickey", "encryption_id", "secret_key_name", "sectet_key_value"};
         this.generateSheet(workbook, "密钥表", headers2, secretKeyList);
         List<Map<String, String>> encryptionfieldList = (List)data.get("field");
         String[] headers3 = new String[]{"id", "createtime", "createuser", "flag", "note", "updatetime", "updateuser", "column_size", "combination_id", "dataareaid", "datasystem_id", "describe_info", "encryption_secretkey_id", "names", "projectid", "table_field_id", "tschemas", "dataareaname", "state", "column_type", "datasystemname", "encryptiontypename", "secretkeyname", "islike", "keepfirst", "encdigit", "realitycolumnsize", "twoindex"};
         this.generateSheet(workbook, "字段和密钥关联表", headers3, encryptionfieldList);
         this.getExportedField(workbook, fileName, response);
      } catch (Exception e) {
         e.printStackTrace();
      }

   }

   public void enctxt(String projectname, Map<String, List> data, HttpServletRequest request, HttpServletResponse response) {
      Date date = new Date();
      String sdate = (new SimpleDateFormat("yyyyMMdd")).format(date);
      String fileName = projectname + "_encrule_backup_" + sdate + ".txt";
      response.setContentType("text/plain");
      response.setCharacterEncoding("UTF-8");
      response.setHeader("content-disposition", "attachment;filename=" + fileName);
      BufferedOutputStream buff = null;
      ServletOutputStream outSTr = null;
      Properties props = new Properties();

      try {
         props = PropertiesLoaderUtils.loadAllProperties("config.properties");
      } catch (IOException e) {
         e.printStackTrace();
      }

      String key = props.getProperty("is_enc_backupfile_key");

      try {
         outSTr = response.getOutputStream();
         buff = new BufferedOutputStream(outSTr);
         List<String> encryptionListString = (List)data.get("enc");
         List<String> secretkeyListString = (List)data.get("key");
         List<String> tCoreEncryptionTypeFieldListString = (List)data.get("field");
         if (null != tCoreEncryptionTypeFieldListString && tCoreEncryptionTypeFieldListString.size() != 0) {
            String estring = StringUtils.join(encryptionListString, "%_%");
            String encestring = SM4Util.encryptEcb(key, estring, "0", (String)null, (String)null, (String)null);
            String sstring = StringUtils.join(secretkeyListString, "%_%");
            String encsstring = SM4Util.encryptEcb(key, sstring, "0", (String)null, (String)null, (String)null);
            String fstring = StringUtils.join(tCoreEncryptionTypeFieldListString, "%_%");
            String encfstring = SM4Util.encryptEcb(key, fstring, "0", (String)null, (String)null, (String)null);
            String enter = "\r\n";
            StringBuffer write = new StringBuffer();
            write.append(encestring).append(enter).append(encsstring).append(enter).append(encfstring);
            buff.write(write.toString().getBytes(StandardCharsets.UTF_8));
            buff.flush();
            buff.close();
         } else {
            StringBuffer write = new StringBuffer();
            buff.write(write.toString().getBytes(StandardCharsets.UTF_8));
            buff.flush();
            buff.close();
         }
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            buff.close();
            outSTr.close();
         } catch (IOException e) {
            e.printStackTrace();
         }

      }

   }

   public void generateSheet(HSSFWorkbook workbook, String sheetname, String[] headers, List<Map<String, String>> datalist) {
      HSSFSheet sheet = null;
      sheet = workbook.createSheet(sheetname);
      HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);
      int columnNum = headers.length;
      HSSFRow headLine = sheet.createRow(0);
      sheet.setDefaultColumnWidth(15);
      if ("密钥表".equals(sheetname)) {
         sheet.setColumnHidden(11, true);
      }

      sheet.setColumnWidth(11, 0);

      for(int n = 0; n < columnNum; ++n) {
         HSSFCell cellRowName = headLine.createCell(n);
         cellRowName.setCellType(1);
         HSSFRichTextString text = new HSSFRichTextString(headers[n]);
         cellRowName.setCellValue(text);
         cellRowName.setCellStyle(columnTopStyle);
      }

      HSSFCellStyle lockstyle = this.getStyle(workbook);
      lockstyle.setAlignment((short)2);
      lockstyle.setVerticalAlignment((short)1);
      lockstyle.setLocked(true);
      HSSFRow dataRow = null;
      int index = 0;

      for(Map mapx : datalist) {
         ++index;
         dataRow = sheet.createRow(index);

         for(int i = 0; i < headers.length; ++i) {
            HSSFCell cell = dataRow.createCell(i);
            String value = (String)mapx.get(headers[i]);
            cell.setCellValue(value);
            cell.setCellStyle(lockstyle);
         }
      }

      sheet.protectSheet("123456");
   }

   public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
      HSSFFont font = workbook.createFont();
      font.setFontHeightInPoints((short)11);
      font.setBoldweight((short)700);
      font.setFontName("微软雅黑");
      HSSFCellStyle style = workbook.createCellStyle();
      style.setBorderBottom((short)1);
      style.setBottomBorderColor((short)8);
      style.setBorderRight((short)1);
      style.setTopBorderColor((short)8);
      style.setTopBorderColor((short)8);
      style.setFont(font);
      style.setWrapText(false);
      style.setAlignment((short)2);
      style.setVerticalAlignment((short)1);
      return style;
   }

   public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
      HSSFFont font = workbook.createFont();
      font.setFontHeightInPoints((short)10);
      font.setBoldweight((short)400);
      font.setFontName("微软雅黑");
      HSSFCellStyle style = workbook.createCellStyle();
      style.setBorderBottom((short)1);
      style.setBottomBorderColor((short)8);
      style.setBorderLeft((short)1);
      style.setLeftBorderColor((short)8);
      style.setBorderRight((short)1);
      style.setRightBorderColor((short)8);
      style.setBorderTop((short)1);
      style.setTopBorderColor((short)8);
      style.setFont(font);
      style.setWrapText(false);
      style.setAlignment((short)2);
      style.setVerticalAlignment((short)1);
      return style;
   }

   public void getExportedField(Workbook workbook, String name, HttpServletResponse response) throws Exception {
      BufferedOutputStream fos = null;

      try {
         response.setContentType("application/x-download");
         response.setHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
         fos = new BufferedOutputStream(response.getOutputStream());
         workbook.write(fos);
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         if (fos != null) {
            fos.close();
         }

      }

   }

   @ResponseBody
   @PostMapping({"/getProjectTree"})
   public Response getProjectTree(@RequestBody TCoreDataProject projectVO) {
      Map<String, Object> treeVO = new HashMap();
      treeVO.put("label", projectVO.getProject());
      treeVO.put("children", this.encryptionConfigService.getProjectChildren(projectVO.getId()));
      return RespHelper.successResp(treeVO);
   }

   @ResponseBody
   @RequestMapping({"/queryBatchOriginalList"})
   public Response queryBatchOriginalList(@RequestBody EncryptionConfigVO vo) {
      String projectId = vo.getProjectid();
      TCoreDataProject project = this.tdataProjectService.selectOneDataProject(projectId);
      HashMap m = this.encryptionConfigService.queryBatchOriginalList(vo);
      List<TCoreEncryptionTypeField> list = (List)m.get("list");
      if (project.getProjectType().equals("udf")) {
         for(int i = 0; i < list.size(); ++i) {
            String tableName = ((TCoreEncryptionTypeField)list.get(i)).getNames();
            tableName = this.udfService.getSourceTable(tableName);
            ((TCoreEncryptionTypeField)list.get(i)).setNames(tableName);
         }
      }

      List<EncTaskTracker.TCoreEncryptionTypeFieldState> listWithExecStatus = EncTaskTracker.instance().fillStates(list);
      int total = (Integer)m.get("total");
      return RespHelper.successResp(listWithExecStatus, total);
   }

   @ResponseBody
   @RequestMapping({"/queryAllEncrypted"})
   public Response queryAllEncrypted(@RequestBody Map<String, String> map) {
      String projectid = (String)map.get("projectid");
      boolean b = this.encryptionConfigService.allEncrypted(projectid);
      return RespHelper.successResp(b);
   }

   @ResponseBody
   @RequestMapping({"/queryIsLike"})
   public Response queryIsLike(@RequestBody Map<String, String> map) {
      String projectid = (String)map.get("projectid");
      String datasystemid = (String)map.get("datasystemid");
      String tableCat = (String)map.get("tablecat");
      String tableName = (String)map.get("tablename");
      String columnName = (String)map.get("columnname");
      List<TCoreEncryptionTypeField> tCoreEncryptionTypeFieldList = this.TCoreEncryptionTypeFieldDao.queryAll(new Criterion[]{Restrictions.eq("projectid", projectid), Restrictions.eq("datasystem_id", datasystemid), Restrictions.eq("tschemas", tableCat), Restrictions.eq("names", tableName), Restrictions.eq("table_field_id", columnName)});
      if (!Objects.isNull(tCoreEncryptionTypeFieldList) && tCoreEncryptionTypeFieldList.size() > 0) {
         TCoreEncryptionTypeField tCoreEncryptionTypeField = (TCoreEncryptionTypeField)tCoreEncryptionTypeFieldList.get(0);
         return StringUtils.isEmpty(tCoreEncryptionTypeField.getIslike()) ? RespHelper.successResp("0") : RespHelper.successResp(tCoreEncryptionTypeField.getIslike());
      } else {
         return RespHelper.successResp("0");
      }
   }

   @ResponseBody
   @RequestMapping({"/queryEncDigit"})
   public Response queryEncDigit(@RequestBody Map<String, String> map) {
      String projectid = (String)map.get("projectid");
      String datasystemid = (String)map.get("datasystemid");
      String tableCat = (String)map.get("tablecat");
      String tableName = (String)map.get("tablename");
      String columnName = (String)map.get("columnname");
      List<TCoreEncryptionTypeField> tCoreEncryptionTypeFieldList = this.TCoreEncryptionTypeFieldDao.queryAll(new Criterion[]{Restrictions.eq("projectid", projectid), Restrictions.eq("datasystem_id", datasystemid), Restrictions.eq("tschemas", tableCat), Restrictions.eq("names", tableName), Restrictions.eq("table_field_id", columnName)});
      Map newmap = new HashMap();
      newmap.put("keepfirst", "0");
      newmap.put("encdigit", "0");
      newmap.put("twoindex", "0");
      if (!Objects.isNull(tCoreEncryptionTypeFieldList) && tCoreEncryptionTypeFieldList.size() > 0) {
         TCoreEncryptionTypeField tCoreEncryptionTypeField = (TCoreEncryptionTypeField)tCoreEncryptionTypeFieldList.get(0);
         newmap.put("keepfirst", StringUtils.isBlank(tCoreEncryptionTypeField.getKeepfirst()) ? "1" : tCoreEncryptionTypeField.getKeepfirst());
         newmap.put("encdigit", StringUtils.isBlank(tCoreEncryptionTypeField.getEncdigit()) ? "0" : tCoreEncryptionTypeField.getEncdigit());
         newmap.put("twoindex", StringUtils.isBlank(tCoreEncryptionTypeField.getTwoindex()) ? "0" : tCoreEncryptionTypeField.getTwoindex());
         return RespHelper.successResp(newmap);
      } else {
         return RespHelper.successResp(newmap);
      }
   }

   @ResponseBody
   @RequestMapping({"/queryColumnSize"})
   public Response queryColumnSize(@RequestBody Map<String, String> map) {
      String projectid = (String)map.get("projectid");
      String datasystemid = (String)map.get("datasystemid");
      String tableCat = (String)map.get("tablecat");
      String tableName = (String)map.get("tablename");
      String columnName = (String)map.get("columnname");
      List<TCoreEncryptionTypeField> tCoreEncryptionTypeFieldList = this.TCoreEncryptionTypeFieldDao.queryAll(new Criterion[]{Restrictions.eq("projectid", projectid), Restrictions.eq("datasystem_id", datasystemid), Restrictions.eq("tschemas", tableCat), Restrictions.eq("names", tableName), Restrictions.eq("table_field_id", columnName)});
      Map newmap = new HashMap();
      newmap.put("columnsize", "");
      if (!Objects.isNull(tCoreEncryptionTypeFieldList) && tCoreEncryptionTypeFieldList.size() > 0) {
         TCoreEncryptionTypeField tCoreEncryptionTypeField = (TCoreEncryptionTypeField)tCoreEncryptionTypeFieldList.get(0);
         newmap.put("columnsize", StringUtils.isBlank(tCoreEncryptionTypeField.getColumn_size()) ? "" : tCoreEncryptionTypeField.getColumn_size());
         return RespHelper.successResp(newmap);
      } else {
         return RespHelper.successResp(newmap);
      }
   }

   @ResponseBody
   @RequestMapping({"/queryExtendColumnSize"})
   public Response queryExtendColumnSize(@RequestBody Map<String, String> map) {
      String projectid = (String)map.get("projectid");
      String datasystemid = (String)map.get("datasystemid");
      String schema = (String)map.get("tablecat");
      String tableName = (String)map.get("tablename");
      String columnName = (String)map.get("columnname");
      String dbtype = (String)map.get("dbtype");
      String columnSize = (String)map.get("columnsize");
      String columntype = (String)map.get("columntype");
      String islike = (String)map.get("islike");
      String encryptionsecretkeyid = (String)map.get("encryptionsecretkeyid");
      Map newmap = new HashMap();
      newmap.put("extendcolumnsize", "");
      if (!"MONGODB".equals(dbtype) && !"ES".equals(dbtype)) {
         if (!"BLOB".equals(columntype) && !"JSON".equals(columntype)) {
            if (!StringUtils.isBlank(columnSize)) {
               if ("0".equals(columnSize)) {
                  return RespHelper.successResp(newmap);
               }

               TCoreSecretkey tCoreSecretkey = (TCoreSecretkey)this.tCoreSecretkeyDao.get(encryptionsecretkeyid);
               TCoreEncryption tCoreEncryption = (TCoreEncryption)this.tCoreEncryptionDao.get(tCoreSecretkey.getEncryption_id());
               String primaryKeyFlag = "0";
               List<com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO> allColumns = this.maksingAppDataRuleService.queryColumnInfo(datasystemid, schema, tableName);
               String primary_key_columns = "";
               String primary_key_col = "";

               for(com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO columnInfoVO : allColumns) {
                  if (columnInfoVO.getPrimarykey().equals("1")) {
                     primary_key_columns = primary_key_columns + columnInfoVO.getColumnname() + ",";
                     if ("DM".equals(dbtype)) {
                        primary_key_col = primary_key_columns + columnInfoVO.getColumnname();
                     } else {
                        primary_key_col = "\"" + primary_key_columns + columnInfoVO.getColumnname() + "\",";
                     }
                  }
               }

               if (!"".equals(primary_key_col) && primary_key_col.charAt(primary_key_col.length() - 1) == ',') {
                  primary_key_col.substring(0, primary_key_col.length() - 1);
               }

               if (!"".equals(primary_key_columns)) {
                  if (primary_key_columns.charAt(primary_key_columns.length() - 1) == ',') {
                     primary_key_columns = primary_key_columns.substring(0, primary_key_columns.length() - 1);
                  }

                  String[] fileds = primary_key_columns.split(",");
                  if (fileds.length > 0) {
                     for(String filed11 : fileds) {
                        if (columnName.equals(filed11)) {
                           primaryKeyFlag = "1";
                        }
                     }
                  }
               }

               String extendcolumnsize = EncUtils.strColumnSize(dbtype, columntype, columnSize, islike, primaryKeyFlag, tCoreEncryption.getEncryption_type());
               newmap.put("extendcolumnsize", extendcolumnsize);
            }

            return RespHelper.successResp(newmap);
         } else {
            newmap.put("extendcolumnsize", "0");
            return RespHelper.successResp(newmap);
         }
      } else {
         newmap.put("extendcolumnsize", "0");
         return RespHelper.successResp(newmap);
      }
   }
}
