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

import com.chenyang.nse.bussiness.dao.PageInfo;
import com.chenyang.nse.bussiness.dao.core.EngineDao;
import com.chenyang.nse.bussiness.dao.table.core.TCoreDatasystemDao;
import com.chenyang.nse.bussiness.dao.table.core.TCoreEngineDao;
import com.chenyang.nse.bussiness.dao.table.core.TCoreMaskingtaskDao;
import com.chenyang.nse.bussiness.dao.table.core.TCoreSubsetDao;
import com.chenyang.nse.bussiness.dao.table.core.TCoreSubsetcolumnsDao;
import com.chenyang.nse.bussiness.dao.table.core.TCoreSubsettaskDao;
import com.chenyang.nse.bussiness.dao.table.core.masking.TCoreMaskingRuleinfoDao;
import com.chenyang.nse.bussiness.dao.table.core.temporary.TCoreMonitorTemporaryDao;
import com.chenyang.nse.bussiness.engine.infa.InfoProperty;
import com.chenyang.nse.bussiness.engine.infa.powercenter961.maskdata.ParamBean;
import com.chenyang.nse.bussiness.engine.infa.powercenter961.pubbean.CommonBean;
import com.chenyang.nse.bussiness.engine.infa.powercenter961.pubbean.MappletMakeDatabean;
import com.chenyang.nse.bussiness.engine.infa.powercenter961.pubbean.SourceBean;
import com.chenyang.nse.bussiness.engine.infa.powercenter961.pubbean.TargetBean;
import com.chenyang.nse.bussiness.engine.infa.powercenter961.subsetdata.ChildMppletCollectiveUtil;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystem;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystemengine;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreEngine;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreSubset;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreSubsetcolumns;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreSubsettask;
import com.chenyang.nse.bussiness.entity.orm.table.core.masking.TCoreMaskingRuleinfo;
import com.chenyang.nse.bussiness.entity.orm.table.core.masking.TCoreMaskingTask;
import com.chenyang.nse.bussiness.entity.orm.table.core.temporary.TCoreMonitorTemporary;
import com.chenyang.nse.bussiness.entity.vo.SubsetTaskEngineVO;
import com.chenyang.nse.bussiness.enumeration.EdbType;
import com.chenyang.nse.bussiness.service.console.DBFieldTypesService;
import com.chenyang.nse.bussiness.service.core.DataSystemService;
import com.chenyang.nse.bussiness.service.core.SubsetService;
import com.chenyang.nse.bussiness.service.info.InfoService;
import com.chenyang.nse.bussiness.tools.datatime.DateTimeTool;
import com.chenyang.nse.bussiness.tools.jdbc.JdbcTool;
import com.chenyang.nse.bussiness.tools.object.ObjectTool;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hibernate.criterion.Criterion;
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 SubsetServiceImpl implements SubsetService {
   @Autowired
   private TCoreSubsetDao tCoreSubsetDao;
   @Autowired
   private TCoreSubsetcolumnsDao tCoreSubsetcolumnsDao;
   @Autowired
   private TCoreSubsettaskDao tCoreSubsettaskDao;
   @Autowired
   private DataSystemService dataSystemService;
   @Autowired
   private DBFieldTypesService dbFieldTypesService;
   @Autowired
   private TCoreEngineDao tCoreEngineDao;
   @Autowired
   private TCoreMaskingRuleinfoDao tCoreMaskingRuleinfoDao;
   @Autowired
   private EngineDao engineDao;
   @Autowired
   private TCoreMaskingtaskDao tCoreMaskingtaskDao;
   @Autowired
   private InfoService infoService;
   @Autowired
   private TCoreDatasystemDao tCoreDatasystemDao;
   @Autowired
   private TCoreMonitorTemporaryDao tCoreMonitorTemporaryDao;

   public boolean checkSubsetName(String subsetName) {
      return this.tCoreSubsetDao.count(new Criterion[]{Restrictions.eq("name", subsetName)}) > 0L;
   }

   private List<TCoreSubsettask> querySubsetTask(String subsetId) {
      List<TCoreSubsettask> taskList = this.tCoreSubsettaskDao.queryAll(new Criterion[]{Restrictions.eq("subsetid", subsetId)});
      return taskList;
   }

   public TCoreSubset saveSubsetAndColumns(TCoreSubset subset, List<String> subsetColumns) {
      if (subset.getId() != null) {
         this.tCoreSubsetcolumnsDao.remove(new Criterion[]{Restrictions.eq("subsetid", subset.getId())});
         this.tCoreSubsetcolumnsDao.getSession().flush();
         this.tCoreSubsetDao.saveOrUpdate(subset);
         List<TCoreSubsettask> taskList = this.querySubsetTask(subset.getId());
         if (taskList != null) {
            for(TCoreSubsettask task : taskList) {
               this.updateSubsetTask(task.getId(), "3");
            }
         }
      } else {
         this.tCoreSubsetDao.save(subset);
      }

      for(String columnData : subsetColumns) {
         String[] datas = columnData.split("，", -1);
         TCoreSubsetcolumns column = null;
         if (datas.length > 8) {
            column = new TCoreSubsetcolumns(subset.getId(), datas[0], datas[1], datas[2], datas[3], datas[4], datas[5], "", datas[7], datas[8]);
         } else if (datas.length > 7) {
            column = new TCoreSubsetcolumns(subset.getId(), datas[0], datas[1], datas[2], datas[3], datas[4], datas[5], "", datas[6], datas[7]);
         } else {
            column = new TCoreSubsetcolumns(subset.getId(), datas[0], datas[1], datas[2], datas[3], datas[4], datas[5], "", (String)null, (String)null);
         }

         column.setUpdatetime(DateTimeTool.getSysTimeDate((String)null));
         this.tCoreSubsetcolumnsDao.save(column);
      }

      return subset;
   }

   public List<TCoreSubset> querySubset(String dataSystemId, String schema) {
      return this.tCoreSubsetDao.queryAll(Order.asc("name"), new Criterion[]{Restrictions.eq("datasystemid", dataSystemId), Restrictions.eq("schema", schema)});
   }

   public List<TCoreSubsetcolumns> querySubsetColumns(String subsetid) {
      return this.tCoreSubsetcolumnsDao.querySubsetColumns(subsetid);
   }

   public void delete(String id) {
      this.tCoreSubsetcolumnsDao.remove(new Criterion[]{Restrictions.eq("subsetid", id)});
      this.tCoreSubsetDao.removeById(id);
   }

   public void deleteByName(String subsetName) {
      this.tCoreSubsetDao.remove(new Criterion[]{Restrictions.eq("name", subsetName)});
   }

   public List<TCoreSubset> queryAllSubset() {
      return this.tCoreSubsetDao.queryAllSubset();
   }

   public List<TCoreSubsettask> queryTask(PageInfo pageInfo) {
      return this.tCoreSubsettaskDao.querySubsetTask(pageInfo);
   }

   public List<TCoreSubsettask> queryTaskByEngineId(String engineid, PageInfo pageInfo) {
      return this.tCoreSubsettaskDao.queryTaskByEngineId(engineid, pageInfo);
   }

   public void updateSubsetTask(String taskId, String status) {
      TCoreSubsettask subsetTask = (TCoreSubsettask)this.tCoreSubsettaskDao.get(taskId);
      subsetTask.setStatus(status);
      this.tCoreSubsettaskDao.update(subsetTask);
   }

   public boolean checkTaskName(String taskName) {
      return this.tCoreSubsettaskDao.count(new Criterion[]{Restrictions.eq("taskname", taskName)}) > 0L;
   }

   public void deleteSubsetTask(String subsetTaskId) {
      this.tCoreSubsettaskDao.removeById(subsetTaskId);
      TCoreMaskingTask suMaskingTask = (TCoreMaskingTask)this.tCoreMaskingtaskDao.get(subsetTaskId);
      if (null != suMaskingTask) {
         this.tCoreMaskingtaskDao.removeById(subsetTaskId);
      }

   }

   public TCoreSubset querySubsetById(String id) {
      return (TCoreSubset)this.tCoreSubsetDao.get(id);
   }

   public TCoreSubsettask queryTaskById(String id) {
      return this.tCoreSubsettaskDao.queryTaskById(id);
   }

   public String saveSubsetTask(TCoreSubsettask subsetTask, String userid) {
      TCoreDatasystem sourceDataSystem = this.dataSystemService.getSubDataSystem(subsetTask.getSourcedatasystemparentid(), subsetTask.getSourceschema());
      TCoreDatasystem targetDataSystem = this.dataSystemService.getSubDataSystem(subsetTask.getTargetdatasystemparentid(), subsetTask.getTargetschema());
      subsetTask.setSourcedatasystemid(sourceDataSystem.getId());
      subsetTask.setTargetdatasystemid(targetDataSystem.getId());
      subsetTask.setStatus("0");
      if (subsetTask.getId() == null) {
         subsetTask.setCreatetime(new Date());
         subsetTask.setUpdatetime(subsetTask.getCreatetime());
         TCoreMaskingTask maskingTask = new TCoreMaskingTask();
         String taskName = subsetTask.getTaskname();
         maskingTask.setTaskname(taskName);
         maskingTask.setCreatetime(subsetTask.getCreatetime());
         maskingTask.setFlag("sub-db");
         maskingTask.setNote(subsetTask.getNote());
         maskingTask.setEngineid(subsetTask.getEngineid());
         maskingTask.setUserid(userid);
         if (!this.infoService.isFolderExist(subsetTask.getEngineid(), subsetTask.getFoldername())) {
            this.infoService.createFolderInEngine(subsetTask.getEngineid(), subsetTask.getFoldername());
         }

         maskingTask.setFdname(subsetTask.getFoldername());
         this.tCoreMaskingtaskDao.save(maskingTask);
         subsetTask.setTaskid(maskingTask.getId());
         this.tCoreSubsettaskDao.save(subsetTask);
      } else {
         subsetTask.setUpdatetime(new Date());
         this.tCoreSubsettaskDao.getSession().update(subsetTask);
         this.saveMaskingTask(subsetTask, false, userid);
         TCoreMaskingTask maskingTask = (TCoreMaskingTask)this.tCoreMaskingtaskDao.get(subsetTask.getTaskid());
         this.tCoreMaskingtaskDao.update(maskingTask);
      }

      return subsetTask.getId();
   }

   private void saveMaskingTask(TCoreSubsettask subsetTask, boolean save, String userid) {
      TCoreMaskingTask maskingTask;
      if (save) {
         maskingTask = new TCoreMaskingTask();
         maskingTask.setId(subsetTask.getId());
      } else {
         maskingTask = (TCoreMaskingTask)this.tCoreMaskingtaskDao.get(subsetTask.getId());
      }

      String taskName = subsetTask.getTaskname();
      maskingTask.setTaskname(taskName);
      maskingTask.setCreatetime(subsetTask.getCreatetime());
      maskingTask.setFlag("sub-db");
      maskingTask.setNote(subsetTask.getNote());
      maskingTask.setEngineid(subsetTask.getEngineid());
      maskingTask.setUserid(userid);
      if (!this.infoService.isFolderExist(subsetTask.getEngineid(), subsetTask.getFoldername())) {
         this.infoService.createFolderInEngine(subsetTask.getEngineid(), subsetTask.getFoldername());
      }

      maskingTask.setFdname(subsetTask.getFoldername());
      if (save) {
         this.tCoreMaskingtaskDao.save(maskingTask);
      } else {
         this.tCoreMaskingtaskDao.getSession().update(maskingTask);
      }

   }

   private String generateTask(TCoreSubsettask subsetTask, List<String> changedRuleIds) {
      try {
         List<TCoreSubsetcolumns> allColumns = this.querySubsetColumns(subsetTask.getSubsetid());
         Map<String, List<TCoreSubsetcolumns>> tableColumns = new HashMap();
         Set<String> hasFKTables = new HashSet();
         Set<String> allTableNames = new HashSet();
         Map<String, List<String>> mainTableChildTableMap = new HashMap();
         Map<String, List<String>> subTableChildTableMap = new HashMap();

         for(TCoreSubsetcolumns column : allColumns) {
            String tableName = column.getTablename();
            allTableNames.add(tableName);
            if (!tableColumns.containsKey(tableName)) {
               tableColumns.put(tableName, new ArrayList());
            }

            ((List)tableColumns.get(tableName)).add(column);
            String key = column.getTkey();
            if (!"0".equals(key) && !"1".equals(key)) {
               String mainTableName = column.getMaintable();
               if (!mainTableChildTableMap.containsKey(mainTableName)) {
                  mainTableChildTableMap.put(mainTableName, new ArrayList());
               }

               if (!((List)mainTableChildTableMap.get(mainTableName)).contains(tableName)) {
                  ((List)mainTableChildTableMap.get(mainTableName)).add(tableName);
               }

               hasFKTables.add(tableName);
               if (!subTableChildTableMap.containsKey(tableName)) {
                  subTableChildTableMap.put(tableName, new ArrayList());
               }

               if (!((List)subTableChildTableMap.get(tableName)).contains(mainTableName)) {
                  ((List)subTableChildTableMap.get(tableName)).add(mainTableName);
               }
            }
         }

         String firstTableName = null;

         for(String name : allTableNames) {
            if (!hasFKTables.contains(name)) {
               firstTableName = name;
               break;
            }
         }

         List<String> sortedTables = new ArrayList();
         sortedTables.add(firstTableName);
         List<String> childTables = (List)mainTableChildTableMap.get(firstTableName);
         sortedTables.addAll(childTables);

         while(true) {
            List<String> tempChildTables = new ArrayList();

            for(String tempName : childTables) {
               if (mainTableChildTableMap.containsKey(tempName)) {
                  for(String child : mainTableChildTableMap.get(tempName)) {
                     if (!sortedTables.contains(child)) {
                        tempChildTables.add(child);
                        sortedTables.add(child);
                     }
                  }
               }
            }

            if (tempChildTables.size() <= 0) {
               String taskname = subsetTask.getTaskname();
               String sourceDataSystemId = subsetTask.getSourcedatasystemid();
               String targetDataSystemId = subsetTask.getTargetdatasystemid();
               String engineId = subsetTask.getEngineid();
               TCoreDatasystemengine sdata = this.infoService.getDatasystemEngine(sourceDataSystemId, engineId);
               TCoreDatasystemengine tdata = this.infoService.getDatasystemEngine(targetDataSystemId, engineId);
               List<SourceBean> sbList = new ArrayList();
               List<TargetBean> tbList = new ArrayList();
               String source_ownername = subsetTask.getSourceschema();
               String target_ownername = subsetTask.getTargetschema();
               TCoreDatasystem datasource = (TCoreDatasystem)this.tCoreDatasystemDao.get(sourceDataSystemId);
               TCoreDatasystem datatarget = (TCoreDatasystem)this.tCoreDatasystemDao.get(targetDataSystemId);
               String prefix = subsetTask.getPrefix();
               prefix = null == prefix ? "" : prefix;

               for(String tableName : sortedTables) {
                  SourceBean sb = new SourceBean();
                  sb.setSo_name(tableName);
                  sb.setSo_ownname("");
                  sb.setBusinessname("");
                  if ("MYSQL".equals(datasource.getDbtype())) {
                     sb.setLinkname(datasource.getDblinkname());
                     sb.setDbdname(datasource.getDblinkname());
                  } else if ("MSSQLSERVER".equals(datasource.getDbtype())) {
                     sb.setLinkname(datasource.getDblinkname());
                     sb.setDbdname(datasource.getDblinkname());
                  } else if ("INFORMIX".equals(datasource.getDbtype())) {
                     sb.setLinkname(datasource.getDblinkname());
                     sb.setDbdname(datasource.getDblinkname());
                  } else if ("SYBASE".equals(datasource.getDbtype())) {
                     sb.setLinkname(datasource.getDblinkname());
                     sb.setDbdname(datasource.getDblinkname());
                  } else {
                     sb.setLinkname("l" + sdata.getDatasystemid());
                     sb.setDbdname(datasource.getDblinkname());
                  }

                  sb.setDatabasetype(datasource.getDbtype());
                  sb.setVersionnumber("1");
                  sb.setObjectversion("1");
                  sb.setDescripion("");
                  sb.setSourceownername(source_ownername);
                  CommonBean cb = new CommonBean();
                  List<String> keytype = new ArrayList();
                  List<String> nameList = new ArrayList();
                  List<String> typeList = new ArrayList();
                  List<String> lengthList = new ArrayList();
                  List<String> scalelist = new ArrayList();
                  List<String> precisionList = new ArrayList();
                  List<MappletMakeDatabean> mappletBeanList = new ArrayList();

                  for(TCoreSubsetcolumns column : tableColumns.get(tableName)) {
                     if (changedRuleIds != null) {
                        for(String changedRuleId : changedRuleIds) {
                           String[] arr = changedRuleId.split("，", -1);
                           if (column.getId().equals(arr[0])) {
                              TCoreSubsetcolumns columnn = (TCoreSubsetcolumns)this.tCoreSubsetcolumnsDao.get(arr[0]);
                              columnn.setRuleid(arr[1]);
                              this.tCoreSubsetcolumnsDao.getSession().update(columnn);
                              TCoreMaskingRuleinfo rulrinfo = (TCoreMaskingRuleinfo)this.tCoreMaskingRuleinfoDao.queryUnique(new Criterion[]{Restrictions.eq("ruleid", arr[1])});
                              if (rulrinfo.getMappletname() != null && !"".equals(rulrinfo.getMappletname())) {
                                 MappletMakeDatabean mappletBean = new MappletMakeDatabean();
                                 mappletBean.setColumnname(column.getColumnname());
                                 mappletBean.setMappletname(rulrinfo.getMappletname());
                                 mappletBeanList.add(mappletBean);
                              }
                           }
                        }
                     }

                     keytype.add(this.getKeyName(column.getTkey()));
                     nameList.add(column.getColumnname());
                     typeList.add(column.getTypename());
                     precisionList.add(column.getColumnsize());
                     lengthList.add(column.getColumnsize());
                     scalelist.add(column.getDecimaldigits());
                  }

                  cb.setKeytype(keytype);
                  cb.setNameList(nameList);
                  cb.setTypeList(typeList);
                  cb.setLengthList(lengthList);
                  cb.setScalelist(scalelist);
                  cb.setPrecisionList(precisionList);
                  sb.setCb(cb);
                  sb.setMappletbean(mappletBeanList);
                  if (subTableChildTableMap.containsKey(tableName)) {
                     sb.setMainTable((List)subTableChildTableMap.get(tableName));
                  }

                  sbList.add(sb);
                  TargetBean tb = new TargetBean();
                  tb.setTar_name(prefix + tableName);
                  tb.setBusinessname("");
                  tb.setConstraint("");
                  tb.setDatabasetype(datatarget.getDbtype());
                  tb.setObjectversion("1");
                  tb.setVersionnumber("1");
                  tb.setDescripion("");
                  tb.setTargetownername(target_ownername);
                  if ("MYSQL".equals(datatarget.getDbtype())) {
                     sb.setLinkname(datatarget.getDblinkname());
                     sb.setDbdname(datatarget.getDblinkname());
                  } else if ("MSSQLSERVER".equals(datatarget.getDbtype())) {
                     sb.setLinkname(datatarget.getDblinkname());
                     sb.setDbdname(datatarget.getDblinkname());
                  } else if ("INFORMIX".equals(datatarget.getDbtype())) {
                     sb.setLinkname(datatarget.getDblinkname());
                     sb.setDbdname(datatarget.getDblinkname());
                  } else if ("SYBASE".equals(datatarget.getDbtype())) {
                     sb.setLinkname(datatarget.getDblinkname());
                     sb.setDbdname(datatarget.getDblinkname());
                  } else {
                     tb.setLinkname("l" + tdata.getDatasystemid());
                     tb.setDbdname(datatarget.getDblinkname());
                  }

                  CommonBean tar = new CommonBean();
                  tar.setKeytype(keytype);
                  tar.setNameList(nameList);
                  tar.setTypeList(typeList);
                  tar.setLengthList(lengthList);
                  tar.setScalelist(scalelist);
                  tar.setPrecisionList(precisionList);
                  tb.setCb(tar);
                  tbList.add(tb);
               }

               String foldername = subsetTask.getFoldername();
               TCoreEngine engine = (TCoreEngine)this.tCoreEngineDao.get(engineId);
               Map<String, Object> map = this.engineDao.queryEnginePropertyKeyValue(engine.getId());
               InfoProperty info = (InfoProperty)ObjectTool.getObjectByMap(InfoProperty.class, map);
               String whereStatements = subsetTask.getWherestatement();
               Map<String, String> querymap = new HashMap();

               for(String querysql : sortedTables) {
                  for(String tableWhereStatement : whereStatements.split(",")) {
                     String[] arr = tableWhereStatement.split(":");
                     if (querysql.equals(arr[0])) {
                        querymap.put(arr[0], arr[1]);
                        break;
                     }

                     querymap.put(querysql, "");
                  }
               }

               ParamBean par_bean = new ParamBean();
               par_bean.setQuerymap(querymap);
               par_bean.setTaskname(taskname);
               par_bean.setFoldername(foldername);
               par_bean.setOwner("");
               par_bean.setGroup("");
               par_bean.setParam_path("");
               par_bean.setPower_repository_version("184.93");
               par_bean.setCodepage("UTF-8");
               par_bean.setRepository_version("184");
               TCoreDatasystem repdata = (TCoreDatasystem)this.tCoreDatasystemDao.get(info.getDatasystemid());
               if (null != repdata) {
                  if ("ORACLE".equals(repdata.getDbtype())) {
                     par_bean.setRepository_dbtype("Oracle");
                  } else if ("DB2".equals(repdata.getDbtype())) {
                     par_bean.setRepository_dbtype("Db2");
                  } else {
                     par_bean.setRepository_dbtype("Oracle");
                  }
               } else {
                  par_bean.setRepository_dbtype("Oracle");
               }

               par_bean.setShard("NOTSHARED");
               ChildMppletCollectiveUtil util = new ChildMppletCollectiveUtil();

               try {
                  util.childMethod(par_bean, sbList, tbList, info);
               } catch (Exception e) {
                  e.printStackTrace();
                  System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
                  System.out.println("生成XML出错");
                  return "生成XML出错";
               }

               this.updateSubsetTask(subsetTask.getId(), "1");
               break;
            }

            childTables = tempChildTables;
         }
      } catch (Exception e) {
         System.out.println("generateTask=================================================================================================================");
         e.printStackTrace();
         System.out.println("generateTask=================================================================================================================");
      }

      return "OK";
   }

   private void setColumnForEngine(String dbType, TCoreSubsetcolumns column) {
      String typeName = column.getTypename();
      String columnSize = column.getColumnsize();
      if (EdbType.ORACLE.toString().equals(dbType)) {
         if ("NUMBER".equals(typeName)) {
            if ("0".equals(columnSize)) {
               column.setTypename("number");
               column.setColumnsize("15");
               column.setDecimaldigits("0");
            } else {
               column.setTypename("number(p,s)");
               column.setDecimaldigits("0");
            }
         } else if (typeName != null && typeName.startsWith("TIMESTAMP")) {
            column.setTypename("TIMESTAMP");
         }
      }

   }

   private String getEngineDBType(String localDBType) {
      if (EdbType.ORACLE.toString().equals(localDBType)) {
         return "Oracle";
      } else if (EdbType.DB2.toString().equals(localDBType)) {
         return "Db2";
      } else {
         return EdbType.INFORMIX.toString().equals(localDBType) ? "Informix" : "";
      }
   }

   private String getKeyName(String keyCode) {
      if ("0".equals(keyCode)) {
         return "NOT A KEY";
      } else if ("1".equals(keyCode)) {
         return "PRIMARY KEY";
      } else if ("2".equals(keyCode)) {
         return "FOREIGN KEY";
      } else {
         return "3".equals(keyCode) ? "PRIMARY/FOREIGN KEY" : "NOT A KEY";
      }
   }

   private String getEngineColumnType(String dbType, String typeName, String columnSize) {
      if (EdbType.ORACLE.toString().equals(dbType) && "NUMBER".equals(typeName)) {
         return "0".equals(columnSize) ? "number" : "number(p,s)";
      } else {
         return typeName;
      }
   }

   public String executeTask(TCoreSubsettask subsetTask) {
      boolean text = this.infoService.importSubMapping(subsetTask.getTaskid());
      boolean flag = true;
      if (!text) {
         flag = false;
         return "生成XML出错";
      } else {
         List<TCoreSubsetcolumns> allColumns = this.querySubsetColumns(subsetTask.getSubsetid());
         Set<String> allTableNames = new HashSet();

         for(TCoreSubsetcolumns column : allColumns) {
            String tableName = column.getTablename();
            allTableNames.add(tableName);
         }

         for(String string : allTableNames) {
            Connection sc = this.dataSystemService.getConnectionByDataSystemId(subsetTask.getSourcedatasystemid());
            Connection tc = this.dataSystemService.getConnectionByDataSystemId(subsetTask.getTargetdatasystemid());
            JdbcTool.copyTable(sc, subsetTask.getSourceschema(), string, tc, subsetTask.getTargetschema(), subsetTask.getPrefix() + string);

            try {
               if (sc != null) {
                  sc.close();
               }

               if (tc != null) {
                  tc.close();
               }
            } catch (Exception var11) {
            }
         }

         long groupId = (new Date()).getTime();
         TCoreMonitorTemporary temporay = new TCoreMonitorTemporary();
         temporay.setGroupid(groupId);
         temporay.setCreatetime(new Date());
         temporay.setTargetname(subsetTask.getTargetdatasystemname());
         temporay.setSourcename(subsetTask.getSourcedatasystemname());
         temporay.setTaskid(subsetTask.getTaskid());
         temporay.setType("数据子集");
         temporay.setWfname(subsetTask.getTaskname());
         this.tCoreMonitorTemporaryDao.save(temporay);
         this.infoService.executeSubMapping(subsetTask.getTaskid());
         return !flag ? "执行错误" : "OK";
      }
   }

   public List<TCoreSubsettask> queryTaskBySubsetId(String subsetId) {
      return this.tCoreSubsettaskDao.queryTaskBySubsetId(subsetId);
   }

   public String saveSubTask(TCoreSubsettask subsetTask, String userid, List<String> changedRuleIds) {
      TCoreDatasystem sourceDataSystem = this.dataSystemService.getSubDataSystem(subsetTask.getSourcedatasystemparentid(), subsetTask.getSourceschema());
      TCoreDatasystem targetDataSystem = this.dataSystemService.getSubDataSystem(subsetTask.getTargetdatasystemparentid(), subsetTask.getTargetschema());
      subsetTask.setSourcedatasystemid(sourceDataSystem.getId());
      subsetTask.setTargetdatasystemid(targetDataSystem.getId());
      subsetTask.setStatus("0");
      if (subsetTask.getId() == null) {
         subsetTask.setCreatetime(new Date());
         subsetTask.setUpdatetime(subsetTask.getCreatetime());
         TCoreMaskingTask maskingTask = new TCoreMaskingTask();
         String taskName = subsetTask.getTaskname();
         maskingTask.setTaskname(taskName);
         maskingTask.setCreatetime(subsetTask.getCreatetime());
         maskingTask.setFlag("sub-db");
         maskingTask.setNote(subsetTask.getNote());
         maskingTask.setEngineid(subsetTask.getEngineid());
         maskingTask.setUserid(userid);
         if (!this.infoService.isFolderExist(subsetTask.getEngineid(), subsetTask.getFoldername())) {
            this.infoService.createFolderInEngine(subsetTask.getEngineid(), subsetTask.getFoldername());
         }

         maskingTask.setFdname(subsetTask.getFoldername());
         this.tCoreMaskingtaskDao.save(maskingTask);
         subsetTask.setTaskid(maskingTask.getId());
         this.tCoreSubsettaskDao.save(subsetTask);
      } else {
         subsetTask.setUpdatetime(new Date());
         this.tCoreSubsettaskDao.getSession().update(subsetTask);
         this.saveMaskingTask(subsetTask, false, userid);
         TCoreMaskingTask maskingTask = (TCoreMaskingTask)this.tCoreMaskingtaskDao.get(subsetTask.getTaskid());
         this.tCoreMaskingtaskDao.update(maskingTask);
      }

      String result = this.generateTask(subsetTask, changedRuleIds);
      System.out.println("保存任务结果：");
      System.out.println(result);
      return subsetTask.getId();
   }

   public String saveSubsetTask(TCoreSubsettask subsetTask, List<String> changedRuleIds, String userid) {
      return this.saveSubTask(subsetTask, userid, changedRuleIds);
   }

   public SubsetTaskEngineVO getEngineInfoOfSubsetTask(String subsetTaskId) {
      return this.tCoreSubsettaskDao.getEngineInfoOfSubsetTask(subsetTaskId);
   }
}
