package com.chenyang.nse.bussiness.tools.dataprocess;

import ch.qos.logback.classic.Logger;
import cn.hutool.core.thread.GlobalThreadPool;
import com.chenyang.nse.bussiness.config.PropertiesLoaderUtils;
import com.chenyang.nse.bussiness.dao.table.core.encryption.TCoreEncryptionTypeFieldDao;
import com.chenyang.nse.bussiness.dao.table.core.encryption.TCoreJiaMiJieMiJinDuDao;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystem;
import com.chenyang.nse.bussiness.entity.orm.table.core.encryption.ColumnPrimaryKeyInfo;
import com.chenyang.nse.bussiness.entity.orm.table.core.encryption.TCoreEncryptionTypeField;
import com.chenyang.nse.bussiness.entity.orm.table.core.encryption.TCoreJiaMiJieMiJinDu;
import com.chenyang.nse.bussiness.entity.vo.strategy.ColumnInfoVO;
import com.chenyang.nse.bussiness.enumeration.EdbType;
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.TCoreEncryptionService;
import com.chenyang.nse.bussiness.service.core.encryption.impl.TCoreEncryptionContext;
import com.chenyang.nse.bussiness.service.core.udf.UdfService;
import com.chenyang.nse.bussiness.tools.dataprocess.common.ColumnBatchInfo;
import com.chenyang.nse.bussiness.tools.dataprocess.common.CustomPolicy;
import com.chenyang.nse.bussiness.tools.dataprocess.common.RecordBatchInfo;
import com.chenyang.nse.bussiness.tools.encryption.EncProvider;
import com.chenyang.nse.bussiness.tools.encryption.EncUtils;
import com.chenyang.nse.bussiness.tools.jdbc.JdbcTool;
import com.chenyang.nse.bussiness.tools.logger.LoggerBuilder;
import com.chenyang.nse.bussiness.tools.propertyutil.PropertyGhcaUtil;
import com.chenyang.nse.bussiness.tools.strategy.StrategyData;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLRecoverableException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.jdbc.core.JdbcTemplate;

public class NewRemoveLoadingTask implements Runnable {
   private String copySuffix = "";
   protected static final String COMPLETE = "7";
   private Logger encryptionlogger;
   protected static final String RUNNING = "-2";
   protected static final String FAIL = "44";
   private int jiamiTasktotalCounts = 0;
   private int jiamiTaskFinishCounts = 0;
   private int failCount = 0;
   private String dataSystemId;
   private String projectId;
   private String tableName;
   private String columnName;
   private String columnType;
   private String columnSize;
   private Connection connection;
   private TCoreDatasystem tCoreDatasystem;
   private String schema;
   private String[] primaryKeys;
   private List<ColumnInfoVO> columnInfoList;
   private List<com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO> allColumnList;
   List<ColumnPrimaryKeyInfo> columnPrimaryKeyInfoList;
   HashSet<ColumnEncryption> columnSet = null;
   Properties props = new Properties();
   private JdbcTemplate jdbcTemplate;
   private boolean isKeepReadData = true;
   private int startRow = 0;
   private int maxPackageCount = 100000;
   boolean encFlag = false;
   EncTaskStateContainer container;
   private static String COLUMN_OUT_OF_RANGE = " 列解密后长度超出范围，请修改列长度";
   private static String CHECK_ALL_COLUMN_OUT_OF_RANGE = " 表解密后校验列合计长度超出数据库要求范围";
   private static String CHECK_COLUMN = "checkColumn";

   public NewRemoveLoadingTask(TCoreDatasystem tCoreDatasystem, String columnSize) {
      this.connection = JdbcTool.getConnection(tCoreDatasystem);
      this.columnSize = columnSize;
   }

   public NewRemoveLoadingTask(String projectId, String dataSystemId, TCoreDatasystem tCoreDatasystem, String schema, String tableName, String[] primaryKeys, List<ColumnInfoVO> columnInfoList, List<ColumnPrimaryKeyInfo> columnPrimaryKeyInfoList, List<com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO> allColumnList) {
      this.copySuffix = PropertyGhcaUtil.copySuffix;
      this.projectId = projectId;
      this.dataSystemId = dataSystemId;
      this.tCoreDatasystem = tCoreDatasystem;
      this.schema = schema;
      this.tableName = tableName;
      this.columnInfoList = columnInfoList;
      this.primaryKeys = primaryKeys;
      this.columnPrimaryKeyInfoList = columnPrimaryKeyInfoList;
      this.allColumnList = allColumnList;
      this.connection = JdbcTool.getConnection(tCoreDatasystem);
      this.jdbcTemplate = (JdbcTemplate)ApplicationContextProvider.getBean(JdbcTemplate.class);

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

      String loggerPath = System.getProperty("user.dir") + File.separator + "encryprocesslog" + File.separator + projectId + File.separator + dataSystemId;
      this.encryptionlogger = (new LoggerBuilder()).getLogger(loggerPath, schema + "." + tableName);
      this.container = EncTaskTracker.instance().container();
      this.container.add(projectId, schema, tableName, columnInfoList);
      EncTaskTracker.instance().register(this.container);
   }

   public void run() {
      try {
         this.runTask();
      } finally {
         EncTaskTracker.instance().over(this.container.getTask());
      }

   }

   public Map<String, Object> runTask() {
      String loggerPath = System.getProperty("user.dir") + File.separator + "encryprocesslog" + File.separator + this.projectId + File.separator + this.dataSystemId;
      Logger encryptionlogger = (new LoggerBuilder()).getLogger(loggerPath, this.schema + "." + this.tableName);
      Thread.currentThread().setName("pool-" + this.tableName + "-thread");
      encryptionlogger.info("启动执行线程！！");
      TCoreJiaMiJieMiJinDuDao tCoreJiaMiJieMiJinDuDao = (TCoreJiaMiJieMiJinDuDao)ApplicationContextProvider.getBean(TCoreJiaMiJieMiJinDuDao.class);
      TCoreEncryptionService tCoreEncryptionService = (TCoreEncryptionService)ApplicationContextProvider.getBean(TCoreEncryptionContext.class);
      HashMap<String, Object> resultMap = new HashMap();
      Boolean doresult = true;
      String selectSQL = "";
      String updateSQL = "";
      StringBuilder selectStrBuilder = new StringBuilder();
      StringBuilder updateStrBuilder = new StringBuilder();
      int cl = this.columnInfoList.size();
      Set<String> columnMap = JdbcTool.getColumnMap(this.connection, this.schema, this.tableName);

      for(int i = 0; i < this.columnInfoList.size(); ++i) {
         this.columnName = ((ColumnInfoVO)this.columnInfoList.get(i)).getColumnName();
         this.columnType = ((ColumnInfoVO)this.columnInfoList.get(i)).getColumnType();
         this.columnSize = ((ColumnInfoVO)this.columnInfoList.get(i)).getColumnSize();
         tCoreEncryptionService.updateFlag(this.projectId, this.dataSystemId, this.schema, this.tableName, this.columnName, "-2");
         String columNamecopy = this.columnName + this.copySuffix;
         if (this.tCoreDatasystem.getDbtype().equals(EdbType.ORACLE.toString())) {
            columNamecopy = "\"" + columNamecopy + "\"";
         }

         if (this.tCoreDatasystem.getDbtype().equals(EdbType.POSTGRESQL.toString()) || this.tCoreDatasystem.getDbtype().equals(EdbType.GAUSS.toString())) {
            columNamecopy = "\"" + columNamecopy + "\"";
         }

         if (this.tCoreDatasystem.getDbtype().equals(EdbType.GREENPLUM.toString())) {
            columNamecopy = "\"" + columNamecopy + "\"";
         }

         if (this.tCoreDatasystem.getDbtype().equals(EdbType.DM.toString())) {
            columNamecopy = "\"" + columNamecopy + "\"";
         }

         if (this.tCoreDatasystem.getDbtype().equals(EdbType.KINGBASE.toString())) {
            columNamecopy = "\"" + columNamecopy + "\"";
         }

         if (this.tCoreDatasystem.getDbtype().equals(EdbType.DB2.toString())) {
            columNamecopy = "\"" + columNamecopy + "\"";
         }

         if (this.tCoreDatasystem.getDbtype().equals(EdbType.ORACLE.toString())) {
            selectStrBuilder.append("\"" + this.columnName + "\"").append(",");
            updateStrBuilder.append("\"" + this.columnName + "\"").append("=?,");
         } else if (!this.tCoreDatasystem.getDbtype().equals(EdbType.POSTGRESQL.toString()) && !this.tCoreDatasystem.getDbtype().equals(EdbType.GAUSS.toString())) {
            if (this.tCoreDatasystem.getDbtype().equals(EdbType.GREENPLUM.toString())) {
               selectStrBuilder.append("\"" + this.columnName + "\"").append(",");
               updateStrBuilder.append("\"" + this.columnName + "\"").append("=?,");
            } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.MSSQLSERVER.toString())) {
               selectStrBuilder.append(this.columnName).append(",");
               updateStrBuilder.append(this.columnName).append("=?,");
            } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.HIVE_TDH.toString())) {
               selectStrBuilder.append(this.columnName).append(",");
               updateStrBuilder.append(this.columnName).append("=?,");
            } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.DM.toString())) {
               selectStrBuilder.append("\"" + this.columnName + "\"").append(",");
               updateStrBuilder.append("\"" + this.columnName + "\"").append("=?,");
            } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.KINGBASE.toString())) {
               selectStrBuilder.append("\"" + this.columnName + "\"").append(",");
               updateStrBuilder.append("\"" + this.columnName + "\"").append("=?,");
            } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.DB2.toString())) {
               selectStrBuilder.append("\"" + this.columnName + "\"").append(",");
               updateStrBuilder.append("\"" + this.columnName + "\"").append("=?,");
            } else {
               selectStrBuilder.append(this.columnName).append(",");
               updateStrBuilder.append(this.columnName).append("=?,");
            }
         } else {
            selectStrBuilder.append("\"" + this.columnName + "\"").append(",");
            updateStrBuilder.append("\"" + this.columnName + "\"").append("=?,");
         }
      }

      TCoreJiaMiJieMiJinDu tCoreJiaMiJieMiJin1 = new TCoreJiaMiJieMiJinDu();
      List<TCoreJiaMiJieMiJinDu> tCoreJiaMiJieMiJinList1 = tCoreJiaMiJieMiJinDuDao.queryTCoreJiaMiJieMiJinDu(this.dataSystemId, this.projectId, this.schema, this.tableName, "0");
      int cpp1 = tCoreJiaMiJieMiJinList1.size();
      if (cpp1 > 0) {
         for(int npp1 = 0; npp1 < cpp1; ++npp1) {
            tCoreJiaMiJieMiJin1 = (TCoreJiaMiJieMiJinDu)tCoreJiaMiJieMiJinList1.get(npp1);
         }
      }

      if (null != tCoreJiaMiJieMiJin1) {
         tCoreJiaMiJieMiJinDuDao.remove(tCoreJiaMiJieMiJin1);
      }

      List<TCoreJiaMiJieMiJinDu> tCoreJiaList = tCoreJiaMiJieMiJinDuDao.queryTCoreJiaMiJieMiJinDu(this.dataSystemId, this.projectId, this.schema, this.tableName, "1");
      int cpppppp = tCoreJiaList.size();
      if (cpppppp == 0) {
         TCoreJiaMiJieMiJinDu tCoreJiaMiJieMiJinDu = new TCoreJiaMiJieMiJinDu();
         tCoreJiaMiJieMiJinDu.setProjectid(this.projectId);
         tCoreJiaMiJieMiJinDu.setDatasystemid(this.dataSystemId);
         tCoreJiaMiJieMiJinDu.setSchemahh(this.schema);
         tCoreJiaMiJieMiJinDu.setTablename(this.tableName);
         tCoreJiaMiJieMiJinDu.setFlag("1");
         tCoreJiaMiJieMiJinDuDao.save(tCoreJiaMiJieMiJinDu);
      }

      if (this.primaryKeys.length > 0) {
         for(int i = 0; i < this.primaryKeys.length; ++i) {
            if (this.tCoreDatasystem.getDbtype().equals(EdbType.ORACLE.toString())) {
               selectStrBuilder.append("\"" + this.primaryKeys[i] + "\"").append(",");
            } else if (!this.tCoreDatasystem.getDbtype().equals(EdbType.POSTGRESQL.toString()) && !this.tCoreDatasystem.getDbtype().equals(EdbType.GAUSS.toString())) {
               if (this.tCoreDatasystem.getDbtype().equals(EdbType.GREENPLUM.toString())) {
                  selectStrBuilder.append("\"" + this.primaryKeys[i] + "\"").append(",");
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.MSSQLSERVER.toString())) {
                  selectStrBuilder.append(this.primaryKeys[i]).append(",");
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.HIVE.toString())) {
                  selectStrBuilder.append(this.primaryKeys[i]).append(",");
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.HIVE_TDH.toString())) {
                  selectStrBuilder.append(this.primaryKeys[i]).append(",");
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.DM.toString())) {
                  selectStrBuilder.append("\"" + this.primaryKeys[i] + "\"").append(",");
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.KINGBASE.toString())) {
                  selectStrBuilder.append("\"" + this.primaryKeys[i] + "\"").append(",");
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.DB2.toString())) {
                  selectStrBuilder.append("\"" + this.primaryKeys[i] + "\"").append(",");
               } else {
                  selectStrBuilder.append(this.primaryKeys[i]).append(",");
               }
            } else {
               selectStrBuilder.append("\"" + this.primaryKeys[i] + "\"").append(",");
            }
         }
      }

      selectStrBuilder.deleteCharAt(selectStrBuilder.length() - 1);
      if (this.tCoreDatasystem.getDbtype().equals(EdbType.DM.toString())) {
         String substring = selectStrBuilder.toString();
         String[] arr = substring.split(",");
         List list = new ArrayList();

         for(int i = 0; i < arr.length; ++i) {
            String s = arr[i].trim();
            if (!list.contains(s)) {
               list.add(s);
            }
         }

         substring = StringUtils.strip(list.toString(), "[]");
         selectStrBuilder.setLength(0);
         selectStrBuilder.append(substring);
      }

      if (this.tCoreDatasystem.getDbtype().equals(EdbType.ORACLE.toString())) {
         selectSQL = "SELECT " + selectStrBuilder.toString() + " FROM \"" + this.schema + "\".\"" + this.tableName + "\"";
      } else if (!this.tCoreDatasystem.getDbtype().equals(EdbType.POSTGRESQL.toString()) && !this.tCoreDatasystem.getDbtype().equals(EdbType.GAUSS.toString())) {
         if (this.tCoreDatasystem.getDbtype().equals(EdbType.GREENPLUM.toString())) {
            selectSQL = "SELECT " + selectStrBuilder.toString() + " FROM \"" + this.schema + "\".\"" + this.tableName + "\"";
         } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.MSSQLSERVER.toString())) {
            selectSQL = "SELECT " + selectStrBuilder.toString() + " FROM " + this.schema + "." + this.tableName;
         } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.HIVE.toString())) {
            selectSQL = "SELECT " + selectStrBuilder.toString() + " FROM " + this.schema + "." + this.tableName;
         } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.HIVE_TDH.toString())) {
            selectSQL = "SELECT " + selectStrBuilder.toString() + " FROM " + this.schema + "." + this.tableName;
         } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.DM.toString())) {
            selectSQL = "SELECT " + selectStrBuilder.toString() + " FROM \"" + this.schema + "\".\"" + this.tableName + "\"";
         } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.KINGBASE.toString())) {
            selectSQL = "SELECT " + selectStrBuilder.toString() + " FROM \"" + this.schema + "\".\"" + this.tableName + "\"";
         } else {
            selectSQL = "SELECT " + selectStrBuilder.toString() + " FROM " + this.schema + "." + this.tableName;
         }
      } else {
         selectSQL = "SELECT " + selectStrBuilder.toString() + " FROM \"" + this.schema + "\".\"" + this.tableName + "\"";
      }

      StringBuilder selectStrBuilder_temp = new StringBuilder(selectSQL);
      selectStrBuilder_temp.append(" order by ");
      if (this.primaryKeys.length > 0) {
         for(int i = 0; i < this.primaryKeys.length; ++i) {
            if (this.tCoreDatasystem.getDbtype().equals(EdbType.ORACLE.toString())) {
               selectStrBuilder_temp.append("\"" + this.primaryKeys[i] + "\"").append(",");
            } else if (!this.tCoreDatasystem.getDbtype().equals(EdbType.POSTGRESQL.toString()) && !this.tCoreDatasystem.getDbtype().equals(EdbType.GAUSS.toString())) {
               if (this.tCoreDatasystem.getDbtype().equals(EdbType.GREENPLUM.toString())) {
                  selectStrBuilder_temp.append("\"" + this.primaryKeys[i] + "\"").append(",");
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.MSSQLSERVER.toString())) {
                  selectStrBuilder_temp.append(this.primaryKeys[i]).append(",");
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.HIVE.toString())) {
                  selectStrBuilder_temp.append(this.primaryKeys[i]).append(",");
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.HIVE_TDH.toString())) {
                  selectStrBuilder_temp.append(this.primaryKeys[i]).append(",");
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.DM.toString())) {
                  selectStrBuilder_temp.append("\"" + this.primaryKeys[i] + "\"").append(",");
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.KINGBASE.toString())) {
                  selectStrBuilder_temp.append("\"" + this.primaryKeys[i] + "\"").append(",");
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.DB2.toString())) {
                  selectStrBuilder_temp.append("\"" + this.primaryKeys[i] + "\"").append(",");
               } else {
                  selectStrBuilder_temp.append(this.primaryKeys[i]).append(",");
               }
            } else {
               selectStrBuilder_temp.append("\"" + this.primaryKeys[i] + "\"").append(",");
            }
         }
      }

      selectStrBuilder_temp.deleteCharAt(selectStrBuilder_temp.length() - 1);
      selectSQL = selectStrBuilder_temp.toString();
      updateStrBuilder.deleteCharAt(updateStrBuilder.length() - 1);
      if (this.tCoreDatasystem.getDbtype().equals(EdbType.ORACLE.toString())) {
         updateSQL = "UPDATE \"" + this.schema + "\".\"" + this.tableName + "\" SET " + updateStrBuilder.toString();
      } else if (!this.tCoreDatasystem.getDbtype().equals(EdbType.POSTGRESQL.toString()) && !this.tCoreDatasystem.getDbtype().equals(EdbType.GAUSS.toString())) {
         if (this.tCoreDatasystem.getDbtype().equals(EdbType.GREENPLUM.toString())) {
            updateSQL = "UPDATE \"" + this.schema + "\".\"" + this.tableName + "\" SET " + updateStrBuilder.toString();
         } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.MSSQLSERVER.toString())) {
            updateSQL = "UPDATE " + this.schema + "." + this.tableName + " SET " + updateStrBuilder.toString();
         } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.HIVE.toString())) {
            updateSQL = "UPDATE " + this.schema + "." + this.tableName + " SET " + updateStrBuilder.toString();
         } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.HIVE_TDH.toString())) {
            updateSQL = "UPDATE " + this.schema + "." + this.tableName + " SET " + updateStrBuilder.toString();
         } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.DM.toString())) {
            updateSQL = "UPDATE \"" + this.schema + "\".\"" + this.tableName + "\" SET " + updateStrBuilder.toString();
         } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.KINGBASE.toString())) {
            updateSQL = "UPDATE \"" + this.schema + "\".\"" + this.tableName + "\" SET " + updateStrBuilder.toString();
         } else {
            updateSQL = "UPDATE `" + this.schema + "`." + this.tableName + " SET " + updateStrBuilder.toString();
         }
      } else {
         updateSQL = "UPDATE \"" + this.schema + "\".\"" + this.tableName + "\" SET " + updateStrBuilder.toString();
      }

      int count = 0;
      if (this.primaryKeys.length > 0) {
         updateSQL = updateSQL + " WHERE ";

         for(int i = 0; i < this.primaryKeys.length; ++i) {
            if (this.tCoreDatasystem.getDbtype().equals(EdbType.ORACLE.toString())) {
               updateSQL = updateSQL + "\"" + this.primaryKeys[i] + "\"=? ";
            } else if (!this.tCoreDatasystem.getDbtype().equals(EdbType.POSTGRESQL.toString()) && !this.tCoreDatasystem.getDbtype().equals(EdbType.GAUSS.toString())) {
               if (this.tCoreDatasystem.getDbtype().equals(EdbType.GREENPLUM.toString())) {
                  updateSQL = updateSQL + "\"" + this.primaryKeys[i] + "\"=? ";
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.MSSQLSERVER.toString())) {
                  updateSQL = updateSQL + this.primaryKeys[i] + "=? ";
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.HIVE.toString())) {
                  updateSQL = updateSQL + this.primaryKeys[i] + "=? ";
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.HIVE_TDH.toString())) {
                  updateSQL = updateSQL + this.primaryKeys[i] + "=? ";
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.DM.toString())) {
                  updateSQL = updateSQL + "\"" + this.primaryKeys[i] + "\"=? ";
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.KINGBASE.toString())) {
                  updateSQL = updateSQL + "\"" + this.primaryKeys[i] + "\"=? ";
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.DB2.toString())) {
                  updateSQL = updateSQL + "\"" + this.primaryKeys[i] + "\"=? ";
               } else {
                  updateSQL = updateSQL + this.primaryKeys[i] + "=? ";
               }
            } else {
               updateSQL = updateSQL + "\"" + this.primaryKeys[i] + "\"=? ";
            }

            ++count;
            if (count < this.primaryKeys.length) {
               updateSQL = updateSQL + " AND ";
            }
         }
      }

      PreparedStatement stmt = null;
      ResultSet rs = null;
      ResultSet rsCount = null;
      PreparedStatement pstmt = null;
      Connection selcon = null;
      int batchMaxCount = 10000;
      if ("OCEANBASE".equals(this.tCoreDatasystem.getDbtype())) {
         int oceanbasecount = 3;

         try {
            Properties properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
            String property = properties.getProperty("oceanbasecount");
            if (property != null && property.length() > 0) {
               oceanbasecount = Integer.valueOf(property.trim());
            }
         } catch (Exception e) {
            for(ColumnInfoVO columnInfoVO : this.columnInfoList) {
               tCoreEncryptionService.updateFlag(this.projectId, this.dataSystemId, this.schema, this.tableName, columnInfoVO.getColumnName(), "4");
            }

            e.printStackTrace();
         }

         batchMaxCount = oceanbasecount;
      } else {
         try {
            Properties properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
            String property = properties.getProperty("encbatchcount");
            if (property != null && property.length() > 0) {
               batchMaxCount = Integer.valueOf(property.trim());
            }
         } catch (Exception e) {
            for(ColumnInfoVO columnInfoVO : this.columnInfoList) {
               tCoreEncryptionService.updateFlag(this.projectId, this.dataSystemId, this.schema, this.tableName, columnInfoVO.getColumnName(), "4");
            }

            e.printStackTrace();
         }
      }

      int curBacthCount = 0;
      PreparedStatement preparedStatementSelect = null;
      ResultSet resultSet = null;

      label1847:
      while(true) {
         try {
            if (!this.tCoreDatasystem.getDbtype().equals("HIVE")) {
               this.connection.setAutoCommit(false);
            }

            encryptionlogger.info("read data sql : {}", selectSQL);
            if (EdbType.MSSQLSERVER.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype())) {
               preparedStatementSelect = this.connection.prepareStatement(selectSQL, 1004, 1007);
            } else {
               preparedStatementSelect = this.connection.prepareStatement(selectSQL, 1003, 1007);
            }

            preparedStatementSelect.setFetchSize(batchMaxCount);
            resultSet = preparedStatementSelect.executeQuery();
            int curBatchCount = 0;
            int totalBatchCount = 0;
            encryptionlogger.info("data loop");
            ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue(1), Executors.defaultThreadFactory(), new CustomPolicy());
            List<RecordBatchInfo> recordBatchInfoList = new ArrayList(10000);

            while(resultSet.next()) {
               List<ColumnBatchInfo> columnBatchInfoList = new ArrayList(this.columnInfoList.size());
               List<String> primaryKeyList = new ArrayList(this.primaryKeys.length);
               RecordBatchInfo recordBatchInfo = new RecordBatchInfo();
               recordBatchInfo.setColumnBatchInfoList(columnBatchInfoList);
               recordBatchInfo.setPrimaryKeyList(primaryKeyList);
               recordBatchInfoList.add(recordBatchInfo);

               for(int i = 0; i < this.columnInfoList.size(); ++i) {
                  ColumnBatchInfo columnBatchInfo = new ColumnBatchInfo();
                  columnBatchInfo.setSecretKey(((ColumnInfoVO)this.columnInfoList.get(i)).getSecretKey());
                  if ("BLOB".equals(((ColumnInfoVO)this.columnInfoList.get(i)).getColumnType())) {
                     columnBatchInfo.setIsBlob(true);
                     Blob blob = resultSet.getBlob(((ColumnInfoVO)this.columnInfoList.get(i)).getColumnName());
                     columnBatchInfo.setBlob(blob);
                  } else {
                     columnBatchInfo.setIsBlob(false);
                     String value = resultSet.getString(((ColumnInfoVO)this.columnInfoList.get(i)).getColumnName());
                     String encryptionType = ((ColumnInfoVO)this.columnInfoList.get(i)).getEncryptionType();
                     String isLike = ((ColumnInfoVO)this.columnInfoList.get(i)).getIsLike();
                     if (!"MYSQL".equals(this.tCoreDatasystem.getDbtype()) && !"MARIADB".equals(this.tCoreDatasystem.getDbtype()) && (((ColumnInfoVO)this.columnInfoList.get(i)).getColumnType().equalsIgnoreCase("char") || ((ColumnInfoVO)this.columnInfoList.get(i)).getColumnType().equalsIgnoreCase("bpchar") || ((ColumnInfoVO)this.columnInfoList.get(i)).getColumnType().equalsIgnoreCase("nchar")) && StringUtils.isNotEmpty(value)) {
                        value = value.trim();
                     }

                     String keepfirst = ((ColumnInfoVO)this.columnInfoList.get(i)).getKeepfirst();
                     String encdigit = ((ColumnInfoVO)this.columnInfoList.get(i)).getEncdigit();
                     String twoindex = ((ColumnInfoVO)this.columnInfoList.get(i)).getTwoindex();
                     columnBatchInfo.setEncryptionType(encryptionType);
                     columnBatchInfo.setValue(value);
                     columnBatchInfo.setIsLike(isLike);
                     columnBatchInfo.setKeepFirst(keepfirst);
                     columnBatchInfo.setEncDigit(encdigit);
                     columnBatchInfo.setTwoIndex(twoindex);
                  }

                  columnBatchInfoList.add(columnBatchInfo);
               }

               for(int i = 0; i < this.primaryKeys.length; ++i) {
                  primaryKeyList.add(resultSet.getString(this.primaryKeys[i]));
               }

               ++curBatchCount;
               if (curBatchCount == batchMaxCount) {
                  String finalUpdateSQL = updateSQL;
                  List<RecordBatchInfo> finalRecordBatchInfoList = recordBatchInfoList;
                  int finalBatchMaxCount = batchMaxCount;
                  executor.submit(() -> {
                     try {
                        this.process(finalUpdateSQL, finalRecordBatchInfoList, finalBatchMaxCount);
                     } finally {
                        finalRecordBatchInfoList.clear();
                        if (finalRecordBatchInfoList instanceof ArrayList) {
                           ((ArrayList) finalRecordBatchInfoList).trimToSize();
                        }

                     }

                  });
                  recordBatchInfoList = new ArrayList(10000);
                  curBatchCount = 0;
               }
            }

            if (curBatchCount > 0) {
               String finalUpdateSQL1 = updateSQL;
               List<RecordBatchInfo> finalRecordBatchInfoList1 = recordBatchInfoList;
               int finalBatchMaxCount1 = batchMaxCount;
               executor.submit(() -> {
                  try {
                     this.process(finalUpdateSQL1, finalRecordBatchInfoList1, finalBatchMaxCount1);
                  } finally {
                     finalRecordBatchInfoList1.clear();
                     if (finalRecordBatchInfoList1 instanceof ArrayList) {
                        ((ArrayList) finalRecordBatchInfoList1).trimToSize();
                     }

                  }

               });
               recordBatchInfoList = null;
            }

            executor.shutdown();
            if (executor.awaitTermination(30L, TimeUnit.MINUTES)) {
               System.out.println("全部完成");
            } else {
               executor.shutdownNow();
               System.out.println("未全部完成，强制停止");
            }
            break;
         } catch (Throwable e) {
            if (!(e instanceof SQLRecoverableException)) {
               encryptionlogger.error("loading task error", e);
               Iterator encryptionConfigService = this.columnInfoList.iterator();

               while(true) {
                  if (!encryptionConfigService.hasNext()) {
                     break label1847;
                  }

                  ColumnInfoVO columnInfoVO = (ColumnInfoVO)encryptionConfigService.next();
                  tCoreEncryptionService.updateFlag(this.projectId, this.dataSystemId, this.schema, this.tableName, columnInfoVO.getColumnName(), "4");
               }
            }

            encryptionlogger.info("db reconnection!");
            this.connection = JdbcTool.getConnection(this.tCoreDatasystem);
         } finally {
            try {
               if (null != preparedStatementSelect) {
                  preparedStatementSelect.close();
               }

               if (null != resultSet) {
                  resultSet.close();
               }
            } catch (Exception e) {
               e.printStackTrace();
            }

         }
      }

      encryptionlogger.info("data loop done");

      try {
         if (!this.encFlag) {
            encryptionlogger.info("解密完成！");

            for(ColumnInfoVO columnInfoVO : this.columnInfoList) {
               String check = this.checkDecryption(this.tCoreDatasystem, columnInfoVO, encryptionlogger, columnMap);
               if (!"ok".equals(check)) {
                  encryptionlogger.error("正常信息：字段" + this.columnName + "加密校验失败");
                  encryptionlogger.error("正常信息：字段" + this.columnName + "回滚完毕");
                  tCoreEncryptionService.updateFlag(this.projectId, this.dataSystemId, this.schema, this.tableName, this.columnName, "44");
               } else {
                  encryptionlogger.info("正常信息：字段" + this.columnName + "解密校验成功");
                  String columnName = columnInfoVO.getColumnName();
                  if (!"MSSQLSERVER".equals(this.tCoreDatasystem.getDbtype()) && !"OCEANBASE".equals(this.tCoreDatasystem.getDbtype()) && !"JSON".equals(columnInfoVO.getColumnType()) && !"BLOB".equals(columnInfoVO.getColumnType()) && (!"ORACLE".equals(this.tCoreDatasystem.getDbtype()) || !columnInfoVO.getColumnType().toLowerCase(Locale.ROOT).equals("char") && !columnInfoVO.getColumnType().toLowerCase(Locale.ROOT).equals("nchar")) && (!"KINGBASE".equals(this.tCoreDatasystem.getDbtype()) || !columnInfoVO.getColumnType().toLowerCase(Locale.ROOT).contains("bpchar"))) {
                     EncryptProcessUtil.rollbackColumnLength(this.connection, encryptionlogger, columnInfoVO, this.tCoreDatasystem, this.schema, this.tableName, this.allColumnList);
                  }

                  tCoreEncryptionService.updateFlag(this.projectId, this.dataSystemId, this.schema, this.tableName, columnName, "7");
                  encryptionlogger.info("正常信息：字段" + columnName + "加密成功，已还原长度");
               }

               try {
                  TCoreEncryptionTypeFieldDao fieldDao = (TCoreEncryptionTypeFieldDao)ApplicationContextProvider.getBean(TCoreEncryptionTypeFieldDao.class);
                  TCoreEncryptionTypeField field = (TCoreEncryptionTypeField)fieldDao.queryUnique(new Criterion[]{Restrictions.eq("id", columnInfoVO.getTcoreencryptionfieldId())});
                  Date date = new Date();
                  field.setCreatetime(date);
                  fieldDao.update(field);
               } catch (Exception var107) {
               }
            }
         }
      } catch (Exception e) {
         encryptionlogger.error(e.getMessage());
         encryptionlogger.warn("提交到" + this.jiamiTaskFinishCounts + "行，执行异常!");

         for(ColumnInfoVO columnInfoVO : this.columnInfoList) {
            tCoreEncryptionService.updateFlag(this.projectId, this.dataSystemId, this.schema, this.tableName, columnInfoVO.getColumnName(), "44");
         }

         try {
            this.connection.rollback();
         } catch (SQLException ex) {
            ex.printStackTrace();
         }

         TCoreJiaMiJieMiJinDu tCoreJiaMiJie = new TCoreJiaMiJieMiJinDu();
         List<TCoreJiaMiJieMiJinDu> tCoreJiaMiJieList = tCoreJiaMiJieMiJinDuDao.queryTCoreJiaMiJieMiJinDu(this.dataSystemId, this.projectId, this.schema, this.tableName, "1");
         int cpplll = tCoreJiaMiJieList.size();
         if (cpplll > 0) {
            for(int npplll = 0; npplll < cpplll; ++npplll) {
               tCoreJiaMiJie = (TCoreJiaMiJieMiJinDu)tCoreJiaMiJieList.get(npplll);
            }
         }

         tCoreJiaMiJie.setState("-1");
         this.failCount += curBacthCount;
         tCoreJiaMiJie.setFailcounts(this.failCount);
         tCoreJiaMiJieMiJinDuDao.update(tCoreJiaMiJie);
      } finally {
         if (stmt != null) {
            try {
               stmt.close();
            } catch (SQLException e) {
               e.printStackTrace();
            }
         }

         if (resultSet != null) {
            try {
               resultSet.close();
            } catch (SQLException e) {
               e.printStackTrace();
            }
         }

         if (rsCount != null) {
            try {
               rsCount.close();
            } catch (SQLException e) {
               e.printStackTrace();
            }
         }

         if (pstmt != null) {
            try {
               pstmt.close();
            } catch (SQLException e) {
               e.printStackTrace();
            }
         }

         if (selcon != null) {
            try {
               selcon.close();
            } catch (SQLException e) {
               e.printStackTrace();
            }
         }

         if (this.connection != null) {
            try {
               this.connection.close();
            } catch (SQLException e) {
               e.printStackTrace();
            }
         }

      }

      try {
         TdataProjectService tdataProjectService = (TdataProjectService)ApplicationContextProvider.getBean(TdataProjectService.class);
         EncryptionConfigService encryptionConfigService = (EncryptionConfigService)ApplicationContextProvider.getBean(EncryptionConfigService.class);
         TCoreEncryptionTypeFieldDao tCoreEncryptionTypeFieldDao = (TCoreEncryptionTypeFieldDao)ApplicationContextProvider.getBean(TCoreEncryptionTypeFieldDao.class);
         StrategyData strategyData = (StrategyData)ApplicationContextProvider.getBean(StrategyData.class);
         UdfService udfService = new UdfService(tdataProjectService, encryptionConfigService, tCoreEncryptionTypeFieldDao, strategyData);
         udfService.loadingColumnParamFinish(this.projectId, this.dataSystemId, this.schema, this.tableName);
      } catch (Exception e) {
         System.out.println(e.getMessage());
      }

      return resultMap;
   }

   /*public <T> Future<T> submitWithCleanup(Callable<T> task, Consumer<T> resultConsumer, Runnable cleanupAction) {
      return GlobalThreadPool.submit(() -> {
         Object var4;
         try {
            T result = (T)task.call();
            if (resultConsumer != null) {
               resultConsumer.accept(result);
            }

            var4 = result;
         } finally {
            if (cleanupAction != null) {
               cleanupAction.run();
            }

         }

         return var4;
      });
   }*/

   private void process(String finalUpdateSQL, List<RecordBatchInfo> finalRecordBatchInfo, int bacthMaxCount) {
      if (finalRecordBatchInfo.size() < bacthMaxCount) {
         this.encryptionlogger.info("执行不满足分页的加密");
      }

      Connection connection = null;
      PreparedStatement pstmt = null;

      try {
         connection = JdbcTool.getConnection(this.tCoreDatasystem);
         if (!this.tCoreDatasystem.getDbtype().equals("HIVE")) {
            connection.setAutoCommit(false);
         }

         pstmt = connection.prepareStatement(finalUpdateSQL);

         for(RecordBatchInfo recordBatchInfoTemp : finalRecordBatchInfo) {
            List<ColumnBatchInfo> columnBatchInfoListTemp = recordBatchInfoTemp.getColumnBatchInfoList();

            for(int i = 0; i < columnBatchInfoListTemp.size(); ++i) {
               ColumnBatchInfo columnBatchInfo = (ColumnBatchInfo)columnBatchInfoListTemp.get(i);
               String value = this.doDecryptionMethod(columnBatchInfo.getEncryptionType(), columnBatchInfo.getSecretKey(), columnBatchInfo.getValue(), columnBatchInfo.getIsLike(), columnBatchInfo.getKeepFirst(), columnBatchInfo.getEncDigit(), columnBatchInfo.getTwoIndex());
               if (columnBatchInfo.getIsBlob()) {
                  pstmt.setBytes(i + 1, value.getBytes(StandardCharsets.ISO_8859_1));
               } else if ("JSON".equals(((ColumnInfoVO)this.columnInfoList.get(i)).getColumnType())) {
                  if (StringUtils.isNotBlank(value)) {
                     String jsonkey = this.props.getProperty("jsonkey");
                     pstmt.setString(i + 1, "{\"" + jsonkey + "\":\"" + value + "\"}");
                  } else {
                     pstmt.setString(i + 1, value);
                  }
               } else {
                  pstmt.setString(i + 1, value);
               }
            }

            List<String> primaryKeyListTemp = recordBatchInfoTemp.getPrimaryKeyList();

            for(int i = 0; i < primaryKeyListTemp.size(); ++i) {
               if (!this.tCoreDatasystem.getDbtype().equals(EdbType.POSTGRESQL.toString()) && !this.tCoreDatasystem.getDbtype().equals(EdbType.GREENPLUM.toString())) {
                  String cname = this.primaryKeys[i];
                  com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO columnInfoVO = (com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO)this.allColumnList.stream().filter((c) -> c.getColumnname().equals(cname)).findFirst().get();
                  if (!this.tCoreDatasystem.getDbtype().equals(EdbType.HIVE.toString()) && !this.tCoreDatasystem.getDbtype().equals(EdbType.HIVE_TDH.toString())) {
                     pstmt.setString(this.columnInfoList.size() + i + 1, (String)primaryKeyListTemp.get(i));
                  } else if (columnInfoVO.getTypename().toLowerCase(Locale.ROOT).contains("int")) {
                     pstmt.setLong(this.columnInfoList.size() + i + 1, Long.parseLong((String)primaryKeyListTemp.get(i)));
                  } else {
                     pstmt.setString(this.columnInfoList.size() + i + 1, (String)primaryKeyListTemp.get(i));
                  }
               } else {
                  String cname = this.primaryKeys[i];
                  com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO columnInfoVO = (com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO)this.allColumnList.stream().filter((c) -> c.getColumnname().equals(cname)).findFirst().get();
                  if (!columnInfoVO.getTypename().toLowerCase(Locale.ROOT).contains("int") && !columnInfoVO.getTypename().toLowerCase(Locale.ROOT).equals("serial") && !columnInfoVO.getTypename().toLowerCase(Locale.ROOT).equals("imos_id") && !columnInfoVO.getTypename().toLowerCase(Locale.ROOT).equals("bigserial")) {
                     pstmt.setString(this.columnInfoList.size() + i + 1, (String)primaryKeyListTemp.get(i));
                  } else {
                     pstmt.setLong(this.columnInfoList.size() + i + 1, Long.parseLong((String)primaryKeyListTemp.get(i)));
                  }
               }
            }

            if (this.tCoreDatasystem.getDbtype().equals("HIVE")) {
               pstmt.executeUpdate();
            } else {
               pstmt.addBatch();
            }
         }

         pstmt.executeBatch();
         pstmt.clearBatch();
         connection.commit();
         this.encryptionlogger.info("解密完成条数为：{}", finalRecordBatchInfo.size());
      } catch (Throwable e) {
         this.encryptionlogger.error("process error 1", e);
         System.out.println(Thread.currentThread().getName() + "-" + e.getMessage());

         try {
            connection.rollback();
         } catch (SQLException ex) {
            this.encryptionlogger.error("process error 2", ex);
            ex.printStackTrace();
         }
      } finally {
         try {
            if (null != pstmt) {
               pstmt.close();
            }

            if (null != connection) {
               connection.close();
            }
         } catch (Throwable e) {
            System.out.println(Thread.currentThread().getName() + "-" + e.getMessage());
         }

         finalRecordBatchInfo.clear();
      }

   }

   public HashMap<String, Object> checkTableColumnLength(HashMap<String, Object> resultMap, String dbType, String columnName, long columnsCheckLength, int columnLength) {
      switch (dbType) {
         case "MYSQL":
            columnsCheckLength += (long)(Integer.parseInt(this.columnSize) * 4);
            if (columnsCheckLength > 65000L) {
               resultMap.put(CHECK_COLUMN, CHECK_ALL_COLUMN_OUT_OF_RANGE);
            }
            break;
         case "MSSQLSERVER":
            columnsCheckLength += (long)Integer.parseInt(this.columnSize);
            if (columnsCheckLength > 8060L) {
               resultMap.put(CHECK_COLUMN, CHECK_ALL_COLUMN_OUT_OF_RANGE);
            }
      }

      return resultMap;
   }

   private String doDecryptionMethod(String encryptionType, String secretKey, String value, String isLike, String keepfirst, String encdigit, String twoindex) throws Exception {
      if (null != encryptionType && !"".equals(encryptionType) && value != null) {
         value = EncProvider.decryptEcb(encryptionType, secretKey, value, isLike, keepfirst, encdigit, twoindex);
      }

      return value;
   }

   private String checkDecryption(TCoreDatasystem tCoreDatasystem, ColumnInfoVO columnInfoVO, Logger encryptionlogger, Set<String> columnMap) {
      if (!columnMap.contains(columnInfoVO.getColumnName() + this.copySuffix)) {
         return "ok";
      } else {
         encryptionlogger.info("开始校验");
         ResultSet rsCount = null;
         int checkNum = Integer.valueOf(this.props.getProperty("checkNum"));
         int sumNum = 0;
         TCoreEncryptionService tCoreEncryptionService = (TCoreEncryptionService)ApplicationContextProvider.getBean(TCoreEncryptionContext.class);

         try {
            Connection conn = JdbcTool.getConnection(tCoreDatasystem);
            Throwable var10 = null;

            try {
               Statement stmt = conn.createStatement();
               Throwable var12 = null;

               try {
                  Boolean bb = true;
                  if (!tCoreDatasystem.getDbtype().equals(EdbType.ORACLE.toString())) {
                     bb = false;
                  }

                  Boolean bbb = true;
                  if (!tCoreDatasystem.getDbtype().equals(EdbType.POSTGRESQL.toString()) && !this.tCoreDatasystem.getDbtype().equals(EdbType.GAUSS.toString())) {
                     bbb = false;
                  }

                  Boolean isGreenplum = true;
                  if (!tCoreDatasystem.getDbtype().equals(EdbType.GREENPLUM.toString())) {
                     isGreenplum = false;
                  }

                  Boolean SQBoolean = true;
                  if (!tCoreDatasystem.getDbtype().equals(EdbType.MSSQLSERVER.toString())) {
                     SQBoolean = false;
                  }

                  Boolean DMBoolean = true;
                  if (!tCoreDatasystem.getDbtype().equals(EdbType.DM.toString())) {
                     DMBoolean = false;
                  }

                  Boolean isHivetdh = true;
                  if (!tCoreDatasystem.getDbtype().equals(EdbType.HIVE_TDH.toString())) {
                     isHivetdh = false;
                  }

                  Boolean isDB2 = true;
                  if (!tCoreDatasystem.getDbtype().equals(EdbType.DB2.toString())) {
                     isDB2 = false;
                  }

                  Boolean isKingbase = true;
                  if (!tCoreDatasystem.getDbtype().equals(EdbType.KINGBASE.toString())) {
                     isKingbase = false;
                  }

                  encryptionlogger.info("正常信息：解密非空校验开始");
                  int iCLimitCount = 0;
                  ResultSet rsC = null;
                  String columnName = columnInfoVO.getColumnName();

                  Exception e;
                  try {
                     if (bb) {
                        String sql1 = "SELECT COUNT(1) AS num FROM(SELECT * FROM ( select ROWNUM RN ,TT.* FROM  (SELECT * FROM \"" + this.schema + "\".\"" + this.tableName + "\" WHERE \"" + columnName + this.copySuffix + "\" IS NOT NULL AND \"" + columnName + "\" IS NULL" + ") TT ) WHERE RN>" + iCLimitCount + " AND RN <= " + checkNum + ")";
                        if (this.columnType.equalsIgnoreCase("clob")) {
                           sql1 = "SELECT COUNT(1) AS num FROM(SELECT * FROM ( select ROWNUM RN ,TT.* FROM  (SELECT * FROM \"" + this.schema + "\".\"" + this.tableName + "\" WHERE \"" + columnName + this.copySuffix + "\" IS NOT NULL AND \"" + columnName + "\" IS  NULL  AND TO_CHAR(\"" + columnName + this.copySuffix + "\") <> ''" + ") TT ) WHERE RN>" + iCLimitCount + " AND RN <= " + checkNum + ")";
                        }

                        rsC = stmt.executeQuery(sql1);
                     } else if (bbb) {
                        rsC = stmt.executeQuery("SELECT count(1) AS num FROM (SELECT * FROM " + this.schema + "." + this.tableName + " WHERE " + columnName + this.copySuffix + " IS NOT NULL AND (" + columnName + " IS NULL  ) offset " + iCLimitCount + " limit " + checkNum + " )t");
                     } else if (isGreenplum) {
                        rsC = stmt.executeQuery("SELECT count(1) AS num FROM (SELECT * FROM " + this.schema + "." + this.tableName + " WHERE " + columnName + this.copySuffix + " IS NOT NULL AND (" + columnName + " IS NULL  ) offset " + iCLimitCount + " limit " + checkNum + " )t");
                     } else if (isHivetdh) {
                        rsC = stmt.executeQuery("SELECT count(1) AS num FROM (SELECT * FROM " + this.schema + "." + this.tableName + " WHERE " + columnName + this.copySuffix + " IS NOT NULL AND (" + columnName + " IS NULL  ) offset " + iCLimitCount + " limit " + checkNum + " )t");
                     } else if (SQBoolean) {
                        rsC = stmt.executeQuery("select  count(1) AS num FROM (  select *, ROW_NUMBER() OVER(Order by " + columnName + " desc ) AS RowId FROM " + this.schema + "." + this.tableName + ") as a  where " + columnName + this.copySuffix + " IS NOT NULL AND " + columnName + " IS NULL and RowId between " + iCLimitCount + " and " + checkNum);
                     } else if (DMBoolean) {
                        rsC = stmt.executeQuery("SELECT COUNT(1) AS num FROM(SELECT * FROM ( select ROWNUM RN ,TT.* FROM  (SELECT * FROM \"" + this.schema + "\".\"" + this.tableName + "\" WHERE \"" + columnName + this.copySuffix + "\" IS NOT NULL AND \"" + columnName + "\" IS NULL) TT ) WHERE RN>" + iCLimitCount + " AND RN <= " + checkNum + ")");
                     } else if (isDB2) {
                        rsC = stmt.executeQuery("SELECT count(1) AS num FROM " + this.schema + "." + this.tableName + " WHERE \"" + columnName + this.copySuffix + "\" IS NOT NULL AND (\"" + columnName + "\" IS NULL  ) limit " + iCLimitCount + " ," + checkNum + "");
                     } else if (isKingbase) {
                        rsC = stmt.executeQuery("SELECT count(1) AS num FROM (SELECT * FROM " + this.schema + "." + this.tableName + " WHERE length(" + columnName + this.copySuffix + ") > 0 AND length(" + columnName + ") = 0 limit " + iCLimitCount + "," + checkNum + " )t");
                     } else {
                        rsC = stmt.executeQuery("SELECT count(1) AS num FROM (SELECT * FROM `" + this.schema + "`." + this.tableName + " WHERE " + columnName + this.copySuffix + " IS NOT NULL AND (" + columnName + " IS NULL ) limit " + iCLimitCount + "," + checkNum + " )t");
                     }

                     int num;
                     for(num = 0; rsC.next(); num = rsC.getInt("num")) {
                     }

                     if (num > 0) {
                        StringBuilder mg = new StringBuilder();
                        mg.append("数据源：");
                        mg.append(this.schema);
                        mg.append("表：");
                        mg.append(this.tableName);
                        mg.append("列：");
                        mg.append(columnName);
                        mg.append("解密后的数据为空，解密失败，准备回滚。");
                        encryptionlogger.info("异常信息：解密非空校验：解密后的数据为空，解密失败，准备回滚。");
                        return mg.toString();
                     }

                     encryptionlogger.info("正常信息：解密非空校验通过");
                  } catch (Exception e1) {
                     e1.printStackTrace();
                  } finally {
                     if (rsC != null) {
                        try {
                           rsC.close();
                        } catch (SQLException e2) {
                           e2.printStackTrace();
                        }
                     }

                  }

                  encryptionlogger.info("正常信息：解密校验开始");
                  int LimitCount = 0;
                  ResultSet rs1 = null;

                  try {
                     byte[] byteArray;
                     try {
                        if (bb) {
                           rs1 = stmt.executeQuery("select nn.\"" + columnName + "\",nn.\"" + columnName + this.copySuffix + "\" from (select t.\"" + columnName + "\",t.\"" + columnName + this.copySuffix + "\",rownum rn from \"" + this.schema + "\".\"" + this.tableName + "\" t) nn where nn.rn>=" + iCLimitCount + "and nn.rn<" + checkNum);
                        } else if (bbb) {
                           rs1 = stmt.executeQuery("select \"" + columnName + "\",\"" + columnName + this.copySuffix + "\" from \"" + this.schema + "\".\"" + this.tableName + "\" OFFSET " + iCLimitCount + " LIMIT " + checkNum);
                        } else if (isGreenplum) {
                           rs1 = stmt.executeQuery("select \"" + columnName + "\",\"" + columnName + this.copySuffix + "\" from \"" + this.schema + "\".\"" + this.tableName + "\" OFFSET " + iCLimitCount + " LIMIT " + checkNum);
                        } else if (SQBoolean) {
                           rs1 = stmt.executeQuery("SELECT " + columnName + "," + columnName + this.copySuffix + ", 0 AS _NAV_ORDER_F_ FROM " + this.schema + "." + this.tableName + " ORDER BY _NAV_ORDER_F_ OFFSET " + iCLimitCount + " ROWS FETCH NEXT " + checkNum + " ROWS ONLY");
                        } else if (isHivetdh) {
                           rs1 = stmt.executeQuery("select " + columnName + "," + columnName + this.copySuffix + " from " + this.schema + "." + this.tableName + " LIMIT " + iCLimitCount + " , " + checkNum);
                        } else if (DMBoolean) {
                           rs1 = stmt.executeQuery("select \"" + columnName + "\",\"" + columnName + this.copySuffix + "\" from \"" + this.schema + "\".\"" + this.tableName + "\" LIMIT " + iCLimitCount + "," + checkNum);
                        } else if (isDB2) {
                           rs1 = stmt.executeQuery("select \"" + columnName + "\",\"" + columnName + this.copySuffix + "\" from \"" + this.schema + "\".\"" + this.tableName + "\" LIMIT " + iCLimitCount + "," + checkNum);
                        } else {
                           rs1 = stmt.executeQuery(this.checkColumn(this.schema, this.tableName, columnName, columnName + this.copySuffix, iCLimitCount, checkNum));
                        }

                        while(rs1.next()) {
                           String copy = "";
                           if ("BLOB".equals(columnInfoVO.getColumnType())) {
                              byteArray = rs1.getBytes(columnName + this.copySuffix);
                              copy = new String(byteArray, StandardCharsets.ISO_8859_1);
                           } else {
                              copy = rs1.getString(columnName + this.copySuffix);
                           }

                           if (StringUtils.isNotEmpty(copy)) {
                              String columnNameN = "";
                              if ("BLOB".equals(columnInfoVO.getColumnType())) {
                                 byte[] byteArray1 = rs1.getBytes(columnName);
                                 columnNameN = new String(byteArray1, StandardCharsets.ISO_8859_1);
                              } else {
                                 columnNameN = rs1.getString(columnName);
                              }

                              String secretKeyId = columnInfoVO.getSecretKeyId();
                              if (!StringUtils.isBlank(columnNameN)) {
                                 String var32;
                                 if ((columnNameN).contains(this.props.getProperty("encryption.label"))) {
                                    Map<String, String> encryptionInfo = tCoreEncryptionService.queryEncryptionInfo(secretKeyId);
                                    if (null != encryptionInfo.get("encryptionType") && !"".equals(encryptionInfo.get("encryptionType"))) {
                                       Boolean isEq = EncUtils.compareStringEq(columnNameN, EncProvider.decryptEcb((String)encryptionInfo.get("encryptionType"), (String)encryptionInfo.get("secretkey"), copy, columnInfoVO.getIsLike(), columnInfoVO.getKeepfirst(), columnInfoVO.getEncdigit(), columnInfoVO.getTwoindex()));
                                       if (!isEq) {
                                          StringBuilder mg111 = new StringBuilder();
                                          mg111.append("数据源：");
                                          mg111.append(this.schema);
                                          mg111.append("表：");
                                          mg111.append(this.tableName);
                                          mg111.append("列：");
                                          mg111.append(columnName);
                                          mg111.append("解密后的数据加密后与元数据不一致，准备回滚。");
                                          var32 = mg111.toString();
                                          return var32;
                                       }
                                    }
                                 } else {
                                    Map<String, String> encryptionInfo = tCoreEncryptionService.queryEncryptionInfo(secretKeyId);
                                    if (null != encryptionInfo.get("encryptionType") && !"".equals(encryptionInfo.get("encryptionType"))) {
                                       Boolean isEq = EncUtils.compareStringEq(columnNameN, copy);
                                       if (!isEq) {
                                          StringBuilder mg111 = new StringBuilder();
                                          mg111.append("数据源：");
                                          mg111.append(this.schema);
                                          mg111.append("表：");
                                          mg111.append(this.tableName);
                                          mg111.append("列：");
                                          mg111.append(columnName);
                                          mg111.append("解密后的数据加密后与原数据不一致，准备回滚。");
                                          encryptionlogger.info("解密后的数据加密后与原数据不一致，准备回滚。");
                                          var32 = mg111.toString();
                                          return var32;
                                       }
                                    }
                                 }
                              }
                           }
                        }

                        encryptionlogger.info("正常信息：解密校验通过");
                     } catch (Exception var135) {
                        e = var135;
                        var135.printStackTrace();
                        encryptionlogger.info("校验出错，结束校验");
                        encryptionlogger.info("错误信息：" + var135.getMessage());
                        return "e1";
                     }
                  } finally {
                     if (rs1 != null) {
                        try {
                           rs1.close();
                        } catch (SQLException e5) {
                           e5.printStackTrace();
                        }
                     }

                  }
               } catch (Throwable var139) {
                  var12 = var139;
                  throw var139;
               } finally {
                  if (stmt != null) {
                     if (var12 != null) {
                        try {
                           stmt.close();
                        } catch (Throwable var132) {
                           var12.addSuppressed(var132);
                        }
                     } else {
                        stmt.close();
                     }
                  }

               }
            } catch (Throwable var141) {
               var10 = var141;
               throw var141;
            } finally {
               if (conn != null) {
                  if (var10 != null) {
                     try {
                        conn.close();
                     } catch (Throwable var131) {
                        var10.addSuppressed(var131);
                     }
                  } else {
                     conn.close();
                  }
               }

            }
         } catch (Exception e) {
            e.printStackTrace();
            encryptionlogger.info("校验出错，结束校验");
            encryptionlogger.info("错误信息：" + e.getMessage());
            return "e2";
         }

         encryptionlogger.info("结束校验");
         return "ok";
      }
   }

   private String checkColumn(String schema, String tableName, String columnName, String checkColumnName, int iCLimitCount, int limitCount) {
      String sql = String.format("SELECT %s,%s FROM %s.%s limit %s,%s", columnName, checkColumnName, schema, tableName, iCLimitCount, limitCount);
      return sql;
   }

   public void deleteCopyColumn(ColumnInfoVO columnInfoVo, String copySuffix, PreparedStatement stmt, Logger encryptionlogger) {
      this.updateFieldFlag(columnInfoVo.getTcoreencryptionfieldId(), "44");
      String rollback;
      if (!this.tCoreDatasystem.getDbtype().equals(EdbType.ORACLE.toString())) {
         rollback = "ALTER TABLE \"" + this.schema + "\".\"" + this.tableName + "\" DROP (\"" + this.columnName + copySuffix + "\")";
      } else if (!this.tCoreDatasystem.getDbtype().equals(EdbType.POSTGRESQL.toString())) {
         rollback = "ALTER TABLE \"" + this.schema + "\".\"" + this.tableName + "\" DROP COLUMN \"" + this.columnName + copySuffix + "\"";
      } else if (!this.tCoreDatasystem.getDbtype().equals(EdbType.MSSQLSERVER.toString())) {
         rollback = this.delCopyColumn(this.schema, this.tableName, this.columnName + copySuffix);
      } else if (!this.tCoreDatasystem.getDbtype().equals(EdbType.DM.toString())) {
         rollback = "ALTER TABLE \"" + this.schema + "\".\"" + this.tableName + "\" DROP COLUMN \"" + this.columnName + copySuffix + "\"";
      } else {
         rollback = this.delCopyColumn(this.schema, this.tableName, this.columnName + copySuffix);
      }

      encryptionlogger.info("解密出错，删除解密列：" + columnInfoVo.getColumnName());

      try {
         stmt.executeUpdate(rollback);
      } catch (SQLException var7) {
         encryptionlogger.info("删除解密列：" + columnInfoVo.getColumnName() + " 失败， sql语句：" + rollback);
      }

   }

   private int updateFieldFlag(String id, String flag) {
      int num = this.jdbcTemplate.update("UPDATE t_core_encryption_field SET flag = ? WHERE id = ?", new Object[]{flag, id});
      return num;
   }

   private String delCopyColumn(String schema, String tableName, String columnName) {
      String sql = String.format("ALTER TABLE %s.%s DROP COLUMN %s", schema, tableName, columnName);
      return sql;
   }

   private boolean isCanKeepRead(ResultSet rs) throws SQLException {
      boolean isCan = true;
      if (!"HIVE".equals(this.tCoreDatasystem.getDbtype()) && !"HIVE_TDH".equals(this.tCoreDatasystem.getDbtype())) {
         rs.last();
         if (rs.getRow() <= 0) {
            isCan = false;
         }

         rs.beforeFirst();
         System.out.println("isCanKeepRead方法:" + isCan);
         return isCan;
      } else {
         return true;
      }
   }

   public String getSqlPaging(String sql1, String sql2) {
      String sqlPaging111 = null;
      if (EdbType.DB2.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype())) {
         sqlPaging111 = "SELECT " + sql1 + " FROM ( select row_number() over() as RN ,TT.* FROM  (" + sql2 + " ) TT ) where RN>" + 1 + " AND RN <= " + 10;
      } else if (!EdbType.ORACLE.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype()) && !EdbType.DM.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype())) {
         if (EdbType.POSTGRESQL.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype())) {
            sqlPaging111 = sql2 + " offset " + 1 + " limit " + 10;
         } else if (EdbType.GREENPLUM.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype())) {
            sqlPaging111 = sql2 + " limit " + 1 + " OFFSET " + 10;
         } else if (!EdbType.MYSQL.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype()) && !EdbType.KINGBASE.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype()) && !EdbType.GAUSS.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype()) && !EdbType.HIVE.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype()) && !EdbType.MARIADB.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype()) && !EdbType.HIVE_TDH.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype())) {
            if (EdbType.MSSQLSERVER.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype())) {
               sqlPaging111 = sql2 + " OFFSET " + 1 + " ROWS FETCH NEXT " + 10 + " ROWS ONLY";
            }
         } else {
            sqlPaging111 = sql2 + " limit " + 1 + "," + 10;
         }
      } else {
         sqlPaging111 = "SELECT " + sql1 + " FROM ( select ROWNUM RN ,TT.* FROM  (" + sql2 + " ) TT ) where RN>" + 1 + " AND RN <= " + 10;
      }

      return sqlPaging111;
   }
}
