package com.chenyang.nse.bussiness.service.core.impl.strategy;

import com.chenyang.nse.bussiness.bean.Column;
import com.chenyang.nse.bussiness.bean.DataBase;
import com.chenyang.nse.bussiness.bean.DataCache;
import com.chenyang.nse.bussiness.bean.Schema;
import com.chenyang.nse.bussiness.bean.Table;
import com.chenyang.nse.bussiness.dao.PageInfo;
import com.chenyang.nse.bussiness.dao.table.core.TCoreDatasystemDao;
import com.chenyang.nse.bussiness.dao.table.core.TCoreDatasystemoracleDao;
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.dao.table.core.strategy.masking.app.MaksingAppDataRuleDao;
import com.chenyang.nse.bussiness.dao.table.core.strategy.masking.relevance.MaksingJoinFieldInfoDao;
import com.chenyang.nse.bussiness.dao.table.core.strategy.masking.relevance.MaksingJoinTableInfoDao;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystem;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystemoracle;
import com.chenyang.nse.bussiness.entity.orm.table.core.dataproject.TCoreSecretkey;
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.strategy.masking.app.MaksingAppDataRule;
import com.chenyang.nse.bussiness.entity.orm.table.core.strategy.masking.relevance.MaksingJoinFieldInfo;
import com.chenyang.nse.bussiness.entity.orm.table.core.strategy.masking.relevance.MaksingJoinTableInfo;
import com.chenyang.nse.bussiness.entity.vo.encyption.EncryptionConfigVO;
import com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO;
import com.chenyang.nse.bussiness.enumeration.EdbType;
import com.chenyang.nse.bussiness.service.core.strategy.MaksingAppDataRuleService;
import com.chenyang.nse.bussiness.tools.es.ElasticSearchUtil;
import com.chenyang.nse.bussiness.tools.es.EsUtil;
import com.chenyang.nse.bussiness.tools.jdbc.JdbcTool;
import com.chenyang.nse.bussiness.tools.jdbc.MongodbTool;
import com.chenyang.nse.bussiness.tools.string.AesTool;
import com.mongodb.MongoClient;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class MaksingAppDataRuleServiceImpl implements MaksingAppDataRuleService {
   @Autowired
   private TCoreDatasystemDao tCoreDatasystemDao;
   @Autowired
   private TCoreDatasystemoracleDao tCoreDatasystemoracleDao;
   @Autowired
   private TCoreSecretkeyDao tCoreSecretkeyDao;
   @Autowired
   private TCoreEncryptionDao tCoreEncryptionDao;
   @Autowired
   private MaksingAppDataRuleDao maksingAppDataRuleDao;
   @Autowired
   private MaksingJoinTableInfoDao maksingJoinTableInfoDao;
   @Autowired
   private MaksingJoinFieldInfoDao maksingJoinFieldInfoDao;
   @Autowired
   TCoreEncryptionTypeFieldDao tCoreEncryptionTypeFieldDao;

   public List<Map<String, String>> querytables(String dataSystemid, List<String> schemas, List<String> tablenames, String tablefield) {
      TCoreDatasystem datasystem = this.queryDataSystemById(dataSystemid);
      String dbtype = datasystem.getDbtype();
      Connection conn = this.getConnectionByDataSystemId(dataSystemid);
      Statement statement = null;
      ResultSet resultSet = null;
      List<Map<String, String>> list = new ArrayList();
      if (conn != null) {
         try {
            StringBuilder sql = new StringBuilder();
            this.searchColumnDiffDatasource(sql, schemas, tablenames, tablefield, dbtype);
            statement = conn.createStatement();
            resultSet = statement.executeQuery(sql.toString());

            while(resultSet.next()) {
               Map<String, String> map = new HashMap();
               map.put("tablename", resultSet.getString("table_name"));
               map.put("schema", resultSet.getString("table_schema"));
               map.put("columnname", resultSet.getString("column_name"));
               list.add(map);
            }
         } catch (Exception e) {
            e.printStackTrace();
         }
      }

      return list;
   }

   private StringBuilder searchColumnDiffDatasource(StringBuilder str, List<String> schemas, List<String> tablenames, String tablefield, String dbtype) {
      if ("MYSQL".equals(dbtype)) {
         str.append("select table_name,table_schema,column_name from information_schema.columns where (1=1");
         if (StringUtils.isNotBlank(tablefield)) {
            str.append(" and column_name ='" + tablefield + "'");
         }

         if (schemas.size() > 0) {
            str.append(" and (1=2");

            for(String schema : schemas) {
               str.append(" or table_schema ='" + schema + "'");
            }

            str.append(")");
         }

         if (tablenames.size() > 0) {
            str.append(" and (1=2");

            for(String tablename : tablenames) {
               str.append(" or table_name ='" + tablename + "'");
            }

            str.append(")");
         }

         str.append(")");
      } else if ("MSSQLSERVER".equals(dbtype)) {
         str.append("SELECT d.name table_name, f.name table_schema, a.name column_name,a.* FROM syscolumns a LEFT JOIN systypes b ON a.usertype = b.usertype INNER JOIN sysobjects d ON a.id = d.id   AND d.name <> 'dtproperties'INNER JOIN sys.schemas f ON  d.uid=f.schema_id LEFT JOIN syscomments e ON a.cdefault = e.id WHERE  d.xtype ='U' and  (1=1");
         if (StringUtils.isNotBlank(tablefield)) {
            str.append(" and a.name ='" + tablefield + "'");
         }

         if (schemas.size() > 0) {
            str.append(" and (1=2");

            for(String schema : schemas) {
               str.append(" or f.name='" + schema + "'");
            }

            str.append(")");
         }

         if (tablenames.size() > 0) {
            str.append(" and (1=2");

            for(String tablename : tablenames) {
               str.append(" or d.name ='" + tablename + "'");
               str.append(")");
            }
         }

         str.append(")");
      } else if ("INFORMIX".equals(dbtype)) {
         str.append("select a.tabname table_name,\"\" table_schema,b.colname column_name from systables a left join syscolumns b on a.tabid=b.tabid where  (1=1");
         if (StringUtils.isNotBlank(tablefield)) {
            str.append(" and  b.colname ='" + tablefield + "'");
         }

         if (tablenames.size() > 0) {
            str.append(" and (1=2");

            for(String tablename : tablenames) {
               str.append(" or a.tabname ='" + tablename + "'");
               str.append(")");
            }
         }

         str.append(")");
      } else if (!"SYBASE_IQ".equals(dbtype)) {
         if ("SYBASE".equals(dbtype)) {
            str.append("SELECT d.name table_name,\"\" table_schema, a.name column_name FROM syscolumns a LEFT JOIN systypes b ON a.usertype = b.usertype INNER JOIN sysobjects d ON a.id = d.id AND d.name <> 'dtproperties' LEFT JOIN syscomments e ON a.cdefault = e.id WHERE  (1=1");
            if (StringUtils.isNotBlank(tablefield)) {
               str.append(" and  a.name ='" + tablefield + "'");
            }

            if (tablenames.size() > 0) {
               str.append(" and (1=2");

               for(String tablename : tablenames) {
                  str.append(" or d.name ='" + tablename + "'");
                  str.append(")");
               }
            }

            str.append(")");
         } else if ("ORACLE".equals(dbtype)) {
            str.append("select table_name,OWNER table_schema,column_name from all_tab_columns where (1=1");
            if (StringUtils.isNotBlank(tablefield)) {
               str.append(" and  column_name ='" + tablefield + "'");
            }

            if (schemas.size() > 0) {
               str.append(" and (1=2");

               for(String schema : schemas) {
                  str.append(" or OWNER = Upper('" + schema + "')");
               }

               str.append(")");
            }

            if (tablenames.size() > 0) {
               str.append(" and (1=2");

               for(String tablename : tablenames) {
                  str.append(" or table_name ='" + tablename + "'");
               }

               str.append(")");
            }

            str.append(")");
         } else if ("DB2".equals(dbtype)) {
            str.append("select table_name,table_schema,column_name from sysibm.columns where (1=1");
            if (StringUtils.isNotBlank(tablefield)) {
               str.append(" and  column_name ='" + tablefield + "'");
            }

            if (schemas.size() > 0) {
               str.append(" and (1=2");

               for(String schema : schemas) {
                  str.append(" or table_schema = '" + schema + "'");
               }

               str.append(")");
            }

            if (tablenames.size() > 0) {
               str.append(" and (1=2");

               for(String tablename : tablenames) {
                  str.append(" or table_name ='" + tablename + "'");
               }

               str.append(")");
            }

            str.append(")");
         } else if ("TERADATA".equals(dbtype)) {
            str.append("select TableName table_name,DatabaseName table_schema,ColumnName column_name from dbc.columns where (1=1");
            if (StringUtils.isNotBlank(tablefield)) {
               str.append(" and ColumnName ='" + tablefield + "'");
            }

            if (schemas.size() > 0) {
               str.append(" and (1=2");

               for(String schema : schemas) {
                  str.append(" or DatabaseName = '" + schema + "'");
               }

               str.append(")");
            }

            if (tablenames.size() > 0) {
               str.append(" and (1=2");

               for(String tablename : tablenames) {
                  str.append(" or TableName ='" + tablename + "'");
               }

               str.append(")");
            }

            str.append(")");
         } else if ("OCEANBASE".equals(dbtype)) {
            str.append("select * from user_tab_columns WHERE TABLE_NAME IN ('");
            if (StringUtils.isNotBlank(tablefield)) {
               str.append(tablefield + "','");
            }

            str = str.delete(str.length() - 2, str.length());
            str.append(")");
         } else if ("DM".equals(dbtype)) {
            str.append("select table_name,OWNER table_schema,column_name from all_tab_columns where (1=1");
            if (StringUtils.isNotBlank(tablefield)) {
               str.append(" and  column_name ='" + tablefield + "'");
            }

            if (schemas.size() > 0) {
               str.append(" and (1=2");

               for(String schema : schemas) {
                  str.append(" or OWNER = Upper('" + schema + "')");
               }

               str.append(")");
            }

            if (tablenames.size() > 0) {
               str.append(" and (1=2");

               for(String tablename : tablenames) {
                  str.append(" or table_name ='" + tablename + "'");
               }

               str.append(")");
            }

            str.append(")");
         }
      }

      return str;
   }

   public List<ColumnInfoVO> queryColumnInfo(String datasystemid, String schema, String tableName) {
      TCoreDatasystem datasystem = this.queryDataSystemById(datasystemid);
      String dbtype = datasystem.getDbtype();
      if ("MONGODB".equals(dbtype)) {
         try {
            MongoClient connect = MongodbTool.connect(schema, datasystem.getUsername(), AesTool.decrypt(datasystem.getPassword(), "ghca"), datasystem.getDbip(), Integer.parseInt(datasystem.getDbport()), true);
            List<Column> columnList = MongodbTool.findAllColumns(connect, schema, tableName);
            List<String> indexes = MongodbTool.findAllIndexes(connect, schema, tableName);
            List<ColumnInfoVO> list1 = new ArrayList();

            for(Column column : columnList) {
               ColumnInfoVO columnInfoVO = new ColumnInfoVO();
               columnInfoVO.setColumnname(column.getColumnName());
               if (columnInfoVO.getColumnname().equals("_id")) {
                  columnInfoVO.setPrimarykey("1");
               } else if (indexes.contains(column.getColumnName())) {
                  columnInfoVO.setPrimarykey("2");
               }

               columnInfoVO.setTablecat(schema);
               columnInfoVO.setTablename(tableName);
               list1.add(columnInfoVO);
            }

            return list1;
         } catch (Exception e) {
            e.printStackTrace();
         }
      } else if ("ES".equals(dbtype)) {
         new EsUtil();

         try {
            List<ColumnInfoVO> list1 = new ArrayList();
            ColumnInfoVO columnId = new ColumnInfoVO();
            columnId.setColumnname("_id");
            columnId.setTypename("text");
            columnId.setTablecat(schema);
            columnId.setTablename(tableName);
            columnId.setPrimarykey("1");
            list1.add(columnId);

            for(String column : ElasticSearchUtil.getFields(datasystem, schema, tableName)) {
               ColumnInfoVO columnInfoVO = new ColumnInfoVO();
               String[] split = column.split("###");
               columnInfoVO.setColumnname(split[0]);
               columnInfoVO.setPrimarykey("0");
               columnInfoVO.setTypename(split[1]);
               columnInfoVO.setTablecat(schema);
               columnInfoVO.setTablename(tableName);
               list1.add(columnInfoVO);
            }

            return list1;
         } catch (Exception e) {
            e.printStackTrace();
         }
      }

      Connection conn = this.getConnectionByDataSystemId(datasystemid);
      List<ColumnInfoVO> list = JdbcTool.getColumnInfoVO(conn, schema, tableName);
      List<ColumnInfoVO> list1 = new ArrayList();
      list = this.updateColumnIndex(schema, tableName, dbtype, conn, list);
      if (datasystem.getDbtype().equals("SYBASE_IQ")) {
         for(ColumnInfoVO civ : list) {
            if (civ.getTypename().equals("varchar") || civ.getTypename().equals("char")) {
               civ.setDecimaldigits("");
            }

            list1.add(civ);
         }
      }

      return datasystem.getDbtype().equals("SYBASE_IQ") ? list1 : list;
   }

   private List<ColumnInfoVO> updateColumnIndex(String schema, String tableName, String dbType, Connection conn, List<ColumnInfoVO> list) {
      String sqlIndex = "";
      if (!dbType.equals("MYSQL") && !dbType.equals("OCEANBASE") && !dbType.equals("MARIADB")) {
         if (dbType.equals("ORACLE")) {
            sqlIndex = "select t.COLUMN_NAME from user_ind_columns t,user_indexes i where t.index_name = i.index_name and t.table_name = i.table_name and t.table_name = '" + tableName + "'";
         } else if (dbType.equals("KINGBASE")) {
            sqlIndex = "select column_name from USER_IND_COLUMNS where table_name = upper('" + tableName + "')";
         } else if (dbType.equals("MSSQLSERVER")) {
            sqlIndex = "SELECT\nTableId=O.[object_id],\nTableName=O.Name,\nIndexId=ISNULL(KC.[object_id],IDX.index_id),\nIndexName=IDX.Name,\nIndexType=ISNULL(KC.type_desc,'Index'),\nIndex_Column_id=IDXC.index_column_id,\nColumnID=C.Column_id,\nColumnName=C.Name,\nSort=CASE INDEXKEY_PROPERTY(IDXC.[object_id],IDXC.index_id,IDXC.index_column_id,'IsDescending')\nWHEN 1 THEN 'DESC' WHEN 0 THEN 'ASC' ELSE '' END,\nPrimaryKey=CASE WHEN IDX.is_primary_key=1 THEN N'√'ELSE N'' END,\n[UQIQUE]=CASE WHEN IDX.is_unique=1 THEN N'√'ELSE N'' END,\nIgnore_dup_key=CASE WHEN IDX.ignore_dup_key=1 THEN N'√'ELSE N'' END,\nDisabled=CASE WHEN IDX.is_disabled=1 THEN N'√'ELSE N'' END,\nFill_factor=IDX.fill_factor,\nPadded=CASE WHEN IDX.is_padded=1 THEN N'√'ELSE N'' END\nFROM sys.indexes IDX\nINNER JOIN sys.index_columns IDXC\nON IDX.[object_id]=IDXC.[object_id]\nAND IDX.index_id=IDXC.index_id\nLEFT JOIN sys.key_constraints KC\nON IDX.[object_id]=KC.[parent_object_id]\nAND IDX.index_id=KC.unique_index_id\nINNER JOIN sys.objects O\nON O.[object_id]=IDX.[object_id]\nINNER JOIN sys.columns C\nON O.[object_id]=C.[object_id]\nAND O.type='U'\nAND O.is_ms_shipped=0\nAND IDXC.Column_id=C.Column_id where O.name='" + tableName + "'";
         } else if (!dbType.equals("POSTGRESQL") && !dbType.equals("GAUSS") && !dbType.equals("GREENPLUM")) {
            if (dbType.equals("DM")) {
               sqlIndex = "SELECT * from DBA_IND_COLUMNS WHERE TABLE_NAME = UPPER('" + tableName + "')";
            } else if (dbType.equals("DB2")) {
               sqlIndex = "SELECT COLNAMES FROM syscat.indexes WHERE tabschema = '" + schema + "' AND tabname='" + tableName + "' ";
            }
         } else {
            sqlIndex = "SELECT\n    t.relname AS TABLE_NAME,\n    i.relname AS index_name,\n    a.attname AS column_name\nFROM\n    pg_class t,\n    pg_class i,\n    pg_index ix,\n    pg_attribute a\nWHERE\n    t.oid = ix.indrelid\n    AND i.oid = ix.indexrelid\n    AND a.attrelid = t.oid\n    AND a.attnum = ANY(ix.indkey)\n    AND t.relkind = 'r'\n    AND t.relname = '" + tableName + "' ORDER BY t.relname, i.relname";
         }
      } else {
         sqlIndex = "show index from " + schema + "." + tableName;
      }

      ResultSet resultSet = null;
      if (StringUtils.isNotEmpty(sqlIndex)) {
         resultSet = this.queryTableIndex(conn, sqlIndex);
      }

      try {
         String indexColumnName = "";

         List<String> indexList;
         for(indexList = new ArrayList(); resultSet != null && resultSet.next(); indexList.add(indexColumnName.toUpperCase(Locale.ROOT))) {
            if (!dbType.equals("MYSQL") && !dbType.equals("OCEANBASE") && !dbType.equals("MARIADB")) {
               if (dbType.equals("ORACLE")) {
                  indexColumnName = resultSet.getString("COLUMN_NAME");
               } else if (dbType.equals("KINGBASE")) {
                  indexColumnName = resultSet.getString("column_name");
               } else if (dbType.equals("MSSQLSERVER")) {
                  indexColumnName = resultSet.getString("ColumnName");
               } else if (!dbType.equals("POSTGRESQL") && !dbType.equals("GAUSS") && !dbType.equals("GREENPLUM")) {
                  if (dbType.equals("DM")) {
                     indexColumnName = resultSet.getString("column_name");
                  } else if (dbType.equals("DB2")) {
                     indexColumnName = resultSet.getString("COLNAMES");
                     indexColumnName = indexColumnName.substring(1);
                  }
               } else {
                  indexColumnName = resultSet.getString("column_name");
               }
            } else {
               indexColumnName = resultSet.getString("Column_name");
            }
         }

         for(ColumnInfoVO civ : list) {
            String columnName = civ.getColumnname().toUpperCase(Locale.ROOT);
            if (Objects.equals(civ.getPrimarykey(), "0") && indexList.contains(columnName)) {
               civ.setPrimarykey("2");
            }
         }
      } catch (SQLException e) {
         e.printStackTrace();
      } finally {
         try {
            if (resultSet != null) {
               resultSet.close();
            }

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

         return list;
      }
   }

   public ResultSet queryTableIndex(Connection conn, String sql) {
      try {
         PreparedStatement pstmt = conn.prepareStatement(sql);
         return pstmt.executeQuery();
      } catch (SQLException e) {
         e.printStackTrace();
         return null;
      }
   }

   public HashMap queryBatchColumnInfo(EncryptionConfigVO vo) {
      HashMap m = new HashMap();
      List<TCoreEncryptionTypeField> tCoreEncryptionTypeFieldList;
      List<TCoreEncryptionTypeField> tCoreEncryptionTypeFieldList1;
      if (vo.getFlag() != null && vo.getFlag().length != 0) {
         tCoreEncryptionTypeFieldList1 = this.tCoreEncryptionTypeFieldDao.queryAll(new Criterion[]{Restrictions.eq("projectid", vo.getProjectid()), Restrictions.ilike("tschemas", vo.getSchema(), MatchMode.ANYWHERE), Restrictions.ilike("datasystemname", vo.getDatasystemname(), MatchMode.ANYWHERE), Restrictions.ilike("names", vo.getTable_name(), MatchMode.ANYWHERE), Restrictions.ilike("table_field_id", vo.getColumnname(), MatchMode.ANYWHERE), Restrictions.ilike("tschemas", vo.getSchema(), MatchMode.ANYWHERE), Restrictions.in("flag", Arrays.asList(vo.getFlag())), Restrictions.eq("state", "0")});
         PageInfo pageInfo = new PageInfo();
         pageInfo.setPageno(vo.getPage());
         pageInfo.setPagesize(vo.getRows());
         ArrayList<Order> orderList = new ArrayList();
         orderList.add(Order.asc("tschemas"));
         orderList.add(Order.asc("names"));
         orderList.add(Order.asc("table_field_id"));
         tCoreEncryptionTypeFieldList = this.tCoreEncryptionTypeFieldDao.queryByPageInfoByOrders(pageInfo, orderList, new Criterion[]{Restrictions.eq("projectid", vo.getProjectid()), Restrictions.ilike("tschemas", vo.getSchema(), MatchMode.ANYWHERE), Restrictions.ilike("datasystemname", vo.getDatasystemname(), MatchMode.ANYWHERE), Restrictions.ilike("names", vo.getTable_name(), MatchMode.ANYWHERE), Restrictions.ilike("table_field_id", vo.getColumnname(), MatchMode.ANYWHERE), Restrictions.ilike("tschemas", vo.getSchema(), MatchMode.ANYWHERE), Restrictions.in("flag", Arrays.asList(vo.getFlag())), Restrictions.eq("state", "0")});
      } else {
         tCoreEncryptionTypeFieldList1 = this.tCoreEncryptionTypeFieldDao.queryAll(new Criterion[]{Restrictions.eq("projectid", vo.getProjectid()), Restrictions.ilike("tschemas", vo.getSchema(), MatchMode.ANYWHERE), Restrictions.ilike("datasystemname", vo.getDatasystemname(), MatchMode.ANYWHERE), Restrictions.ilike("names", vo.getTable_name(), MatchMode.ANYWHERE), Restrictions.ilike("table_field_id", vo.getColumnname(), MatchMode.ANYWHERE), Restrictions.ilike("tschemas", vo.getSchema(), MatchMode.ANYWHERE), Restrictions.eq("state", "0")});
         PageInfo pageInfo = new PageInfo();
         pageInfo.setPageno(vo.getPage());
         pageInfo.setPagesize(vo.getRows());
         ArrayList<Order> orderList = new ArrayList();
         orderList.add(Order.asc("tschemas"));
         orderList.add(Order.asc("names"));
         orderList.add(Order.asc("table_field_id"));
         tCoreEncryptionTypeFieldList = this.tCoreEncryptionTypeFieldDao.queryByPageInfoByOrders(pageInfo, orderList, new Criterion[]{Restrictions.eq("projectid", vo.getProjectid()), Restrictions.ilike("tschemas", vo.getSchema(), MatchMode.ANYWHERE), Restrictions.ilike("datasystemname", vo.getDatasystemname(), MatchMode.ANYWHERE), Restrictions.ilike("names", vo.getTable_name(), MatchMode.ANYWHERE), Restrictions.ilike("table_field_id", vo.getColumnname(), MatchMode.ANYWHERE), Restrictions.ilike("tschemas", vo.getSchema(), MatchMode.ANYWHERE), Restrictions.eq("state", "0")});
      }

      int total = tCoreEncryptionTypeFieldList1.size();
      tCoreEncryptionTypeFieldList = this.columnExist(tCoreEncryptionTypeFieldList);

      for(TCoreEncryptionTypeField field : tCoreEncryptionTypeFieldList) {
         TCoreSecretkey tCoreSecretkey = (TCoreSecretkey)this.tCoreSecretkeyDao.get(field.getEncryption_secretkey_id());
         if (tCoreSecretkey != null) {
            field.setSecretkeyname(tCoreSecretkey.getSecret_key_name());
            TCoreEncryption tCoreEncryption = (TCoreEncryption)this.tCoreEncryptionDao.get(tCoreSecretkey.getEncryption_id());
            if (tCoreEncryption != null) {
               field.setEncryptiontypename(tCoreEncryption.getEncryption_name());
            }
         }

         TCoreDatasystem tCoreDatasystem = (TCoreDatasystem)this.tCoreDatasystemDao.get(field.getDatasystem_id());
         if (tCoreDatasystem != null) {
            field.setDatasystemname(tCoreDatasystem.getSysname());
         }
      }

      m.put("list", tCoreEncryptionTypeFieldList);
      m.put("total", total);
      return m;
   }

   public List<TCoreEncryptionTypeField> columnExist(List<TCoreEncryptionTypeField> tCoreEncryptionTypeFieldList) {
      Optional<DataBase> dataBase = null;
      List<DataBase> dataBaseList = DataCache.dataList;
      Optional<Schema> schema = null;
      Optional<Table> table = null;
      Optional<Column> column = null;

      for(TCoreEncryptionTypeField tCoreEncryptionTypeField : tCoreEncryptionTypeFieldList) {
         TCoreDatasystem datasystem = (TCoreDatasystem)this.tCoreDatasystemDao.get(tCoreEncryptionTypeField.getDatasystem_id());
         dataBase = dataBaseList.stream().filter((x) -> x.getDatasystemid().equals(datasystem.getId())).findFirst();
         if (dataBase.isPresent()) {
            List<Schema> schemaList = ((DataBase)dataBase.get()).getSchemaList();
            if (schemaList == null) {
               tCoreEncryptionTypeField.setIsExist("1");
            } else {
               schema = schemaList.stream().filter((s) -> tCoreEncryptionTypeField.getTschemas().equals(s.getName())).findFirst();
               if (schema.isPresent()) {
                  List<Table> tableList = ((Schema)schema.get()).getTableList();
                  if (tableList == null) {
                     tCoreEncryptionTypeField.setIsExist("1");
                  } else {
                     table = tableList.stream().filter((t) -> tCoreEncryptionTypeField.getNames().equals(t.getName())).findFirst();
                     if (table.isPresent()) {
                        List<Column> columnList = ((Table)table.get()).getColumnList();
                        if (columnList == null) {
                           tCoreEncryptionTypeField.setIsExist("1");
                        } else {
                           column = columnList.stream().filter((c) -> tCoreEncryptionTypeField.getTable_field_id().equals(c.getColumnName())).findFirst();
                           if (column.isPresent()) {
                              tCoreEncryptionTypeField.setIsExist("0");
                           } else {
                              tCoreEncryptionTypeField.setIsExist("1");
                           }
                        }
                     } else {
                        tCoreEncryptionTypeField.setIsExist("1");
                     }
                  }
               } else {
                  tCoreEncryptionTypeField.setIsExist("1");
               }
            }
         } else {
            tCoreEncryptionTypeField.setIsExist("1");
         }
      }

      return tCoreEncryptionTypeFieldList;
   }

   public MaksingAppDataRule queryById(String strategyid) {
      return (MaksingAppDataRule)this.maksingAppDataRuleDao.queryUnique(new Criterion[]{Restrictions.eq("id", strategyid)});
   }

   public MaksingJoinTableInfo queryTableById(String id) {
      return (MaksingJoinTableInfo)this.maksingJoinTableInfoDao.queryUnique(new Criterion[]{Restrictions.eq("id", id)});
   }

   public List<MaksingJoinTableInfo> queryTableInfoById(String maskingid) {
      return this.maksingJoinTableInfoDao.queryAll(new Criterion[]{Restrictions.eq("maskingid", maskingid)});
   }

   public List<MaksingJoinFieldInfo> queryFieldInfoById(String tableid) {
      return this.maksingJoinFieldInfoDao.queryAll(new Criterion[]{Restrictions.eq("tableid", tableid)});
   }

   public List<MaksingJoinFieldInfo> queryFieldInfoByDataareaid(String dataareaid) {
      return this.maksingJoinFieldInfoDao.queryAll(new Criterion[]{Restrictions.eq("dataareaid", dataareaid)});
   }

   public void saveRuleInfo(MaksingJoinTableInfo maksingJoinTableInfo) {
      this.maksingJoinTableInfoDao.save(maksingJoinTableInfo);
   }

   public void saveFieldInfo(MaksingJoinFieldInfo maksingJoinFieldInfo) {
      this.maksingJoinFieldInfoDao.save(maksingJoinFieldInfo);
   }

   public void removeStrategy(String strategyid) {
      this.maksingAppDataRuleDao.removeById(strategyid);
   }

   public void removeRuleInfo(String maskingid) {
      this.maksingJoinTableInfoDao.remove(new Criterion[]{Restrictions.eq("maskingid", maskingid)});
   }

   public void removeFieldInfo(String maskingid) {
      this.maksingJoinFieldInfoDao.remove(new Criterion[]{Restrictions.eq("maskingid", maskingid)});
   }

   public void saveRule(MaksingAppDataRule maksingAppDataRule) {
      this.maksingAppDataRuleDao.save(maksingAppDataRule);
   }

   public void updateRule(MaksingAppDataRule maksingAppDataRule) {
      this.maksingAppDataRuleDao.update(maksingAppDataRule);
   }

   public Connection getConnectionByDataSystemId(String datasystemid) {
      TCoreDatasystem datasystem = this.queryDataSystemById(datasystemid);

      try {
         String dbcode = datasystem.getDbtype();
         if (dbcode.equals("ES")) {
            return null;
         } else if (EdbType.KAFKA.getDbname().equalsIgnoreCase(dbcode)) {
            return null;
         } else {
            String ip = datasystem.getDbip();
            String port = datasystem.getDbport();
            String servername = datasystem.getDbservername();
            String server = datasystem.getServername();
            String oracleisins = datasystem.getOracleisins();
            if ("1".equals(oracleisins)) {
               dbcode = "ORACLEINS";
               List<TCoreDatasystemoracle> tCoreDatasystemoracles = this.tCoreDatasystemoracleDao.queryInsByDatasnystemId(datasystem.getId());
               ip = ((TCoreDatasystemoracle)tCoreDatasystemoracles.get(0)).getInsip();
               port = ((TCoreDatasystemoracle)tCoreDatasystemoracles.get(0)).getInsport();
               servername = ((TCoreDatasystemoracle)tCoreDatasystemoracles.get(0)).getInsname();
            }

            String url;
            switch (datasystem.getDbtype()) {
               case "INFORMIX":
                  url = EdbType.getUrlByEdbcode(dbcode, ip, port, servername, server);
                  break;
               case "TERADATA":
                  url = EdbType.getUrlByEdbcode(dbcode, ip, port, servername, server, datasystem.getPagecode());
                  break;
               default:
                  if (StringUtils.isNotBlank(datasystem.getDbip()) && !datasystem.getDbtype().equals(EdbType.GAUSSDB.getDbcode())) {
                     url = EdbType.getUrlByEdbcode(datasystem.getDbtype(), datasystem.getDbip(), datasystem.getDbport(), datasystem.getDbservername());
                  } else {
                     String[] ips = datasystem.getDbip().split(",");
                     String[] ports = datasystem.getDbport().split(",");
                     List<Map<String, String>> ipports = new ArrayList();

                     for(int i = 0; i < ips.length; ++i) {
                        Map<String, String> map = new HashMap();
                        map.put("ip", ips[i]);
                        map.put("port", ports[i]);
                        ipports.add(map);
                     }

                     url = EdbType.getUrlByEdbcode(datasystem.getDbtype(), ipports, datasystem.getDbservername(), datasystem.getDbservername());
                  }
            }

            String username = datasystem.getUsername();
            String password = AesTool.decrypt(datasystem.getPassword(), "ghca");
            String driver = EdbType.getEdbTypeByDbcode(dbcode).getDbdriver();
            if ("HIVE".equals(datasystem.getDbtype()) && "on".equals(datasystem.getIskerberos())) {
               System.setProperty("java.security.krb5.conf", datasystem.getXmlpath() + "/krb5.conf");
               Connection conn = JdbcTool.getKerberosConn(url + ";principal=" + datasystem.getPrincipal(), driver, datasystem.getLoginprincipal(), datasystem.getXmlpath());
               return conn;
            } else if (dbcode.equals("RAPIDSDB")) {
               Connection conn = JdbcTool.getConnection(driver, url, username, "");
               return conn;
            } else {
               Connection conn = JdbcTool.getConnection(driver, url, username, password);
               return conn;
            }
         }
      } catch (Exception var17) {
         return null;
      }
   }

   public Connection getConnection(String datasystemid) throws SQLException, ClassNotFoundException, IOException {
      TCoreDatasystem datasystem = this.queryDataSystemById(datasystemid);
      String dbcode = datasystem.getDbtype();
      String ip = datasystem.getDbip();
      String port = datasystem.getDbport();
      String servername = datasystem.getDbservername();
      String server = datasystem.getServername();
      String oracleisins = datasystem.getOracleisins();
      if ("1".equals(oracleisins)) {
         dbcode = "ORACLEINS";
         List<TCoreDatasystemoracle> tCoreDatasystemoracles = this.tCoreDatasystemoracleDao.queryInsByDatasnystemId(datasystem.getId());
         ip = ((TCoreDatasystemoracle)tCoreDatasystemoracles.get(0)).getInsip();
         port = ((TCoreDatasystemoracle)tCoreDatasystemoracles.get(0)).getInsport();
         servername = ((TCoreDatasystemoracle)tCoreDatasystemoracles.get(0)).getInsname();
      }

      String url;
      switch (datasystem.getDbtype()) {
         case "INFORMIX":
            url = EdbType.getUrlByEdbcode(dbcode, ip, port, servername, server);
            break;
         case "TERADATA":
            url = EdbType.getUrlByEdbcode(dbcode, ip, port, servername, server, datasystem.getPagecode());
            break;
         default:
            if (StringUtils.isNotBlank(datasystem.getDbip()) && !datasystem.getDbtype().equals(EdbType.GAUSSDB.getDbcode())) {
               url = EdbType.getUrlByEdbcode(datasystem.getDbtype(), datasystem.getDbip(), datasystem.getDbport(), datasystem.getDbservername());
            } else {
               String[] ips = datasystem.getDbip().split(",");
               String[] ports = datasystem.getDbport().split(",");
               List<Map<String, String>> ipports = new ArrayList();

               for(int i = 0; i < ips.length; ++i) {
                  Map<String, String> map = new HashMap();
                  map.put("ip", ips[i]);
                  map.put("port", ports[i]);
                  ipports.add(map);
               }

               url = EdbType.getUrlByEdbcode(datasystem.getDbtype(), ipports, datasystem.getDbservername(), datasystem.getDbservername());
            }
      }

      String username = datasystem.getUsername();
      String password = "1".equals(datasystem.getFlag()) ? AesTool.decrypt(datasystem.getPassword(), "ghca") : datasystem.getPassword();
      String driver = EdbType.getEdbTypeByDbcode(dbcode).getDbdriver();
      if ("HIVE".equals(datasystem.getDbtype()) && "on".equals(datasystem.getIskerberos())) {
         System.setProperty("java.security.krb5.conf", datasystem.getXmlpath() + "/krb5.conf");
         Connection conn = JdbcTool.getKerberosConnect(url + ";principal=" + datasystem.getPrincipal(), driver, datasystem.getLoginprincipal(), datasystem.getXmlpath());
         return conn;
      } else if (dbcode.equals("RAPIDSDB")) {
         Connection conn = JdbcTool.getconnection(driver, url, username, "");
         return conn;
      } else {
         Connection conn = JdbcTool.getconnection(driver, url, username, password);
         return conn;
      }
   }

   public TCoreDatasystem queryDataSystemById(String id) {
      return (TCoreDatasystem)this.tCoreDatasystemDao.get(id);
   }

   public void updateMaskingStatus(String id, String status) {
      MaksingAppDataRule info = (MaksingAppDataRule)this.maksingAppDataRuleDao.queryUnique(new Criterion[]{Restrictions.eq("id", id)});
      info.setEnablestatus(status);
      this.maksingAppDataRuleDao.update(info);
   }

   public List<MaksingAppDataRule> getMaksingInfoByDataSystemById(String datasystemid) {
      return this.maksingAppDataRuleDao.queryAll(new Criterion[]{Restrictions.eq("datasystemid", datasystemid), Restrictions.eq("enablestatus", "1")});
   }
}
