package com.chenyang.nse.bussiness.service.info.tool;

import com.chenyang.nse.bussiness.dao.table.core.TCoreDatasystemDao;
import com.chenyang.nse.bussiness.dao.table.core.TCoreMaskingtaskDao;
import com.chenyang.nse.bussiness.dao.table.core.masking.TCoreMaskingDetailrecordDao;
import com.chenyang.nse.bussiness.dao.table.core.masking.TCoreMaskingFilesystemDao;
import com.chenyang.nse.bussiness.dao.table.core.masking.TCoreMaskingTableDao;
import com.chenyang.nse.bussiness.dao.table.core.masking.TCoreMaskingTaskrecordDao;
import com.chenyang.nse.bussiness.dao.table.core.masking.TCoreSyncKeyindexDao;
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.basic.webservice.SessionBean;
import com.chenyang.nse.bussiness.engine.infa.basic.webservice.SessionBeanDetail;
import com.chenyang.nse.bussiness.engine.infa.basic.webservice.StartWorkFlowWebService;
import com.chenyang.nse.bussiness.engine.infa.basic.wsclient.DIServiceInfo;
import com.chenyang.nse.bussiness.engine.infa.basic.wsclient.DataIntegrationInterface;
import com.chenyang.nse.bussiness.engine.infa.basic.wsclient.DataIntegrationService;
import com.chenyang.nse.bussiness.engine.infa.basic.wsclient.Fault;
import com.chenyang.nse.bussiness.engine.infa.basic.wsclient.LoginRequest;
import com.chenyang.nse.bussiness.engine.infa.basic.wsclient.SessionHeader;
import com.chenyang.nse.bussiness.engine.infa.basic.wsclient.WorkflowRequest;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystem;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreImporttask;
import com.chenyang.nse.bussiness.entity.orm.table.core.masking.TCoreMaskingDetailrecord;
import com.chenyang.nse.bussiness.entity.orm.table.core.masking.TCoreMaskingTable;
import com.chenyang.nse.bussiness.entity.orm.table.core.masking.TCoreMaskingTask;
import com.chenyang.nse.bussiness.entity.orm.table.core.masking.TCoreMaskingTaskrecord;
import com.chenyang.nse.bussiness.entity.orm.table.core.masking.TCoreSyncKeyindex;
import com.chenyang.nse.bussiness.entity.orm.table.core.maskingself.TCoreMaskingselfTask;
import com.chenyang.nse.bussiness.entity.orm.table.core.temporary.TCoreMonitorTemporary;
import com.chenyang.nse.bussiness.enumeration.EdbType;
import com.chenyang.nse.bussiness.enumeration.EmaskingTaskType;
import com.chenyang.nse.bussiness.service.core.AllwaysMonitorService;
import com.chenyang.nse.bussiness.service.info.InfoService;
import com.chenyang.nse.bussiness.tools.command.CommandTool;
import com.chenyang.nse.bussiness.tools.jdbc.JdbcTool;
import com.chenyang.nse.bussiness.tools.net.FtpTool;
import com.chenyang.nse.bussiness.tools.net.SFTPUtil;
import com.chenyang.nse.bussiness.tools.string.AesTool;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.ws.Holder;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@EnableAsync
@Transactional
public class InfoToolImpl implements InfoTool {
   @Autowired
   private TCoreMaskingTableDao tCoreMaskingtableDao;
   @Autowired
   private TCoreDatasystemDao tCoreDatasystemDao;
   @Autowired
   private AllwaysMonitorService allwaysMonitorService;
   @Autowired
   private TCoreMaskingTaskrecordDao tCoreMaskingTaskrecordDao;
   @Autowired
   private TCoreMaskingDetailrecordDao tCoreMaskingDetailrecordDao;
   @Autowired
   private TCoreMonitorTemporaryDao tCoreMonitorTemporaryDao;
   @Autowired
   private TCoreSyncKeyindexDao tCoreSyncKeyindexDao;
   @Autowired
   private InfoService infoService;
   @Autowired
   private TCoreMaskingtaskDao tCoreMaskingtaskDao;
   @Autowired
   private TCoreMaskingFilesystemDao tCoreMaskingFilesystemDao;

   public void StartWorkflow(InfoProperty engine, String folderName, String workflowName) throws Exception {
      if (StringUtils.isNoneBlank(new CharSequence[]{workflowName}) && !workflowName.startsWith("wf_")) {
         workflowName = "wf_" + workflowName;
      }

      DataIntegrationInterface webService = (new DataIntegrationService()).getDataIntegration();
      LoginRequest loginRequest = new LoginRequest();
      loginRequest.setRepositoryDomainName(engine.getDomainname());
      loginRequest.setRepositoryName(engine.getRepository());
      loginRequest.setUserName(engine.getUsername());
      loginRequest.setPassword(engine.getPassword());
      String sessionId = webService.login(loginRequest, (Holder)null);
      SessionHeader sessionHeader = new SessionHeader();
      sessionHeader.setSessionId(sessionId);
      System.out.println(StartWorkFlowWebService.returnStatus(sessionId, engine, workflowName, folderName));
      System.out.println("=========执行-------");
   }

   public String workflowTaskCompleteMonitor(InfoProperty engine, String folderName, String workflowName) {
      if (StringUtils.isNoneBlank(new CharSequence[]{workflowName}) && !workflowName.startsWith("wf_")) {
         workflowName = "wf_" + workflowName;
      }

      String completeStatus = "0";
      DataIntegrationInterface webService = (new DataIntegrationService()).getDataIntegration();
      LoginRequest loginRequest = new LoginRequest();
      loginRequest.setRepositoryDomainName(engine.getDomainname());
      loginRequest.setRepositoryName(engine.getRepository());
      loginRequest.setUserName(engine.getUsername());
      loginRequest.setPassword(engine.getPassword());
      DIServiceInfo dIServiceInfo = new DIServiceInfo();
      dIServiceInfo.setDomainName(engine.getDomainname());
      dIServiceInfo.setServiceName(engine.getInteservicename());
      WorkflowRequest workflowRequest = new WorkflowRequest();
      workflowRequest.setDIServiceInfo(dIServiceInfo);
      workflowRequest.setFolderName(folderName);
      workflowRequest.setWorkflowName(workflowName);

      try {
         String sessionId = webService.login(loginRequest, (Holder)null);
         SessionHeader sessionHeader = new SessionHeader();
         sessionHeader.setSessionId(sessionId);
         webService.waitTillWorkflowComplete(workflowRequest, sessionHeader);
      } catch (Fault var11) {
      }

      completeStatus = "1";
      return completeStatus;
   }

   public void synchronizeForeignKey(TCoreMaskingTask task, String mappingkey) {
      try {
         TCoreMaskingTable stable = (TCoreMaskingTable)this.tCoreMaskingtableDao.queryUnique(new Criterion[]{Restrictions.eq("datadirection", "0"), Restrictions.eq("mappingkey", mappingkey), Restrictions.eq("taskid", task.getId())});
         TCoreMaskingTable ttable = (TCoreMaskingTable)this.tCoreMaskingtableDao.queryUnique(new Criterion[]{Restrictions.eq("datadirection", "1"), Restrictions.eq("mappingkey", mappingkey), Restrictions.eq("taskid", task.getId())});
         if ("true".equalsIgnoreCase(task.getIsprimary())) {
            Connection srcconn = this.getConnectionByDataSystemId(stable.getDatasystemid());
            Connection tarconn = this.getConnectionByDataSystemId(ttable.getDatasystemid());
            JdbcTool.synchronizeForeignKey(srcconn, stable.getDbschema(), stable.getTablename(), tarconn, ttable.getDbschema(), ttable.getTablename());
            JdbcTool.closeConnection(srcconn);
            JdbcTool.closeConnection(tarconn);
         }

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

   public void workflowTaskCompleteMonitorDBToDB(TCoreMaskingTask task, InfoProperty engine, String folderName, String sourceTableName, String userid, String mappingkey, TCoreMonitorTemporary temporay) {
      try {
         Thread.sleep(2000L);
         String completeStatus = this.workflowTaskCompleteMonitor(engine, folderName, sourceTableName);
         if ("1".equals(completeStatus)) {
            System.out.println(">>>>>>>>>>>>>>>>>>workflowTaskCompleteMonitorDBToDB:监控到脱敏任务 - workflow:【" + task.getTaskname() + "】 > folderName：【" + folderName + "】;  workflowName【 wf_" + sourceTableName + "】 任务执行完成。");
            SessionBean sessionBean = this.runlog(task, engine, sourceTableName);
            TCoreMaskingTaskrecord record = new TCoreMaskingTaskrecord();
            record.setTaketime(new Date());
            record.setTaskid(task.getId());
            record.setUserid(userid);
            record.setExeresult(sessionBean.getStatus());
            this.tCoreMaskingTaskrecordDao.save(record);
            TCoreMaskingDetailrecord detail = new TCoreMaskingDetailrecord();
            detail.setSuccessrow(String.valueOf(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getApplied_rows()));
            detail.setFailurerow(String.valueOf(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getRejected_rows()));
            detail.setTaskrecordid(record.getId());
            detail.setStarttime(sessionBean.getStart_time());
            detail.setEndtime(sessionBean.getEnd_time());
            detail.setSourceid(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getTablename());
            detail.setTargetid(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(1)).getTablename());
            this.tCoreMaskingDetailrecordDao.save(detail);
            TCoreMaskingTable stable = (TCoreMaskingTable)this.tCoreMaskingtableDao.queryUnique(new Criterion[]{Restrictions.eq("datadirection", "0"), Restrictions.eq("mappingkey", mappingkey), Restrictions.eq("taskid", task.getId())});
            TCoreMaskingTable ttable = (TCoreMaskingTable)this.tCoreMaskingtableDao.queryUnique(new Criterion[]{Restrictions.eq("datadirection", "1"), Restrictions.eq("mappingkey", mappingkey), Restrictions.eq("taskid", task.getId())});
            TCoreSyncKeyindex sync = new TCoreSyncKeyindex();
            sync.setTasktableid(stable.getTablename());
            sync.setTaskid(task.getId());
            if ("true".equalsIgnoreCase(task.getIsprimary())) {
               Connection srcconn = this.getConnectionByDataSystemId(stable.getDatasystemid());
               Connection tarconn = this.getConnectionByDataSystemId(ttable.getDatasystemid());
               sync.setKeystarttime(new Date());
               JdbcTool.synchronizePrimaryKey(srcconn, stable.getDbschema(), stable.getTablename(), tarconn, ttable.getDbschema(), ttable.getTablename());
               sync.setKeyendtime(new Date());
               JdbcTool.closeConnection(srcconn);
               JdbcTool.closeConnection(tarconn);
            }

            if ("true".equalsIgnoreCase(task.getIsindex())) {
               Connection srcconn = this.getConnectionByDataSystemId(stable.getDatasystemid());
               Connection tarconn = this.getConnectionByDataSystemId(ttable.getDatasystemid());
               sync.setIndexstarttime(new Date());
               JdbcTool.synchronizeIndex(srcconn, stable.getDbschema(), stable.getTablename(), tarconn, ttable.getDbschema(), ttable.getTablename());
               sync.setIndexendtime(new Date());
               JdbcTool.closeConnection(srcconn);
               JdbcTool.closeConnection(tarconn);
            }

            this.tCoreSyncKeyindexDao.save(sync);
            System.out.println(">>>>>>> sessionBean.getStatus()：" + sessionBean.getStatus());
            if ("SUCCEEDED".equals(sessionBean.getStatus())) {
               temporay.setFlag("1");
            } else if ("FAILED".equals(sessionBean.getStatus())) {
               temporay.setFlag("2");
            }

            this.tCoreMonitorTemporaryDao.saveOrUpdate(temporay);
            this.tCoreMonitorTemporaryDao.getSession().getTransaction().commit();
            this.tCoreMonitorTemporaryDao.getSession().getTransaction().begin();
         }
      } catch (Exception e) {
         e.printStackTrace();
      }

   }

   @Async
   public void curTaskAllWorkflowCompleteMonitor(TCoreMaskingTask task, InfoProperty engineInfo, List<TCoreMaskingTable> tlist, HashMap<String, TCoreMaskingTable> sourceTableMaps, String userid, Map<String, TCoreMonitorTemporary> ttmap) {
      for(TCoreMaskingTable tCoreMaskingTable : tlist) {
         String sourceTableName = ((TCoreMaskingTable)sourceTableMaps.get(tCoreMaskingTable.getMappingkey())).getTablename();
         if (null != ttmap && ttmap.containsKey(sourceTableName)) {
            TCoreMonitorTemporary temporay = (TCoreMonitorTemporary)ttmap.get(sourceTableName);
            if (sourceTableMaps.get(tCoreMaskingTable.getMappingkey()) != null) {
               this.updateDataConut((TCoreMaskingTable)sourceTableMaps.get(tCoreMaskingTable.getMappingkey()), temporay);
            }

            this.workflowTaskCompleteMonitorDBToDB(task, engineInfo, task.getFdname(), sourceTableName, userid, tCoreMaskingTable.getMappingkey(), temporay);
         }
      }

      for(TCoreMaskingTable tCoreMaskingTable : tlist) {
         this.synchronizeForeignKey(task, tCoreMaskingTable.getMappingkey());
      }

   }

   @Async
   public void quartzFileTask(TCoreMaskingTask task, InfoProperty engine, String name, String userid, TCoreMonitorTemporary temporay, Map<String, String> map) {
      try {
         Thread.sleep(5000L);
         String completeStatus = this.workflowTaskCompleteMonitor(engine, task.getFdname(), name);
         String filepath = (String)map.get("filepath");
         String filename = (String)map.get("filename");
         String type = (String)map.get("type");
         File file = new File(filepath + filename);
         File file_source = new File(filepath + "w" + filename);
         if ("1".equals(completeStatus)) {
            System.out.println(">>>>>>>>>>>>>>>>>>workflowTaskCompleteMonitorFILE:监控到脱敏任务 - workflow:【" + task.getTaskname() + "】 > folderName：【" + task.getFdname() + "】;  workflowName【 wf_" + name + "】 任务执行完成。");
            SessionBean sessionBean = this.runlog(task, engine, name);
            String path = engine.getXmldir() + File.separator + task.getTaskname() + File.separator;
            if (!"".equals(sessionBean.getStatus()) && sessionBean.getStatus() != null) {
               TCoreMaskingTaskrecord record = new TCoreMaskingTaskrecord();
               record.setTaketime(new Date());
               record.setTaskid(task.getId());
               record.setUserid(userid);
               record.setExeresult(sessionBean.getStatus());
               this.tCoreMaskingTaskrecordDao.save(record);
               TCoreMaskingDetailrecord detail = new TCoreMaskingDetailrecord();
               detail.setSuccessrow(String.valueOf(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getApplied_rows()));
               detail.setFailurerow(String.valueOf(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getRejected_rows()));
               detail.setTaskrecordid(record.getId());
               detail.setStarttime(sessionBean.getStart_time());
               detail.setEndtime(sessionBean.getEnd_time());
               detail.setSourceid(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getTablename());
               detail.setTargetid(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(1)).getTablename());
               this.tCoreMaskingDetailrecordDao.save(detail);
               if (type.equals("1")) {
                  String netfilepath = (String)map.get("netfilepath");
                  String netfilename = (String)map.get("netfilename");
                  String datasystenid = (String)map.get("datasystenid");
                  if (null != datasystenid) {
                     TCoreDatasystem filesystem = (TCoreDatasystem)this.tCoreDatasystemDao.get(datasystenid);
                     if (filesystem.getDbtype().equals("SFTP")) {
                        String username = filesystem.getUsername();
                        String password = filesystem.getPassword();
                        String host = filesystem.getDbip();
                        Integer port = Integer.parseInt(filesystem.getDbport());
                        SFTPUtil sftp = new SFTPUtil(username, password, host, port);
                        SFTPUtil.login();
                        InputStream is = new FileInputStream(file);
                        sftp.upload(netfilepath, netfilename, is);
                        is.close();
                        sftp.logout();
                     } else if (filesystem.getDbtype().equals("FTP")) {
                        String username = filesystem.getUsername();
                        String password = filesystem.getPassword();
                        String host = filesystem.getDbip();
                        Integer port = Integer.parseInt(filesystem.getDbport());
                        InputStream is = new FileInputStream(file);
                        FtpTool.uploadFile(host, port, username, password, netfilepath, netfilename, is);
                        is.close();
                     }
                  }
               }

               if ("SUCCEEDED".equals(sessionBean.getStatus())) {
                  temporay.setFlag("1");
               } else if ("FAILED".equals(sessionBean.getStatus())) {
                  temporay.setFlag("2");
               }

               this.tCoreMonitorTemporaryDao.saveOrUpdate(temporay);
            }
         }

         if (file.exists()) {
            file.delete();
         }

         if (file_source.exists()) {
            file_source.delete();
         }
      } catch (Exception e) {
         e.printStackTrace();
      }

   }

   @Async
   public void quartzDB(TCoreMaskingTask task, InfoProperty engine, String name, String userid, String mappingkey, TCoreMonitorTemporary temporay) {
      try {
         Thread.sleep(5000L);
         SessionBean sessionBean = this.runlog(task, engine, name);
         DataIntegrationInterface webService = null;
         if (!"SUCCEED".equals(sessionBean.getStatus()) && !"RUNNING".equals(sessionBean.getStatus()) && !"".equals(sessionBean.getStatus()) && sessionBean.getStatus() != null) {
            TCoreMaskingTaskrecord record = new TCoreMaskingTaskrecord();
            record.setTaketime(new Date());
            record.setTaskid(task.getId());
            record.setUserid(userid);
            record.setExeresult(sessionBean.getStatus());
            this.tCoreMaskingTaskrecordDao.save(record);
            TCoreMaskingDetailrecord detail = new TCoreMaskingDetailrecord();
            detail.setSuccessrow(String.valueOf(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getApplied_rows()));
            detail.setFailurerow(String.valueOf(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getRejected_rows()));
            detail.setTaskrecordid(record.getId());
            detail.setStarttime(sessionBean.getStart_time());
            detail.setEndtime(sessionBean.getEnd_time());
            detail.setSourceid(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getTablename());
            detail.setTargetid(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(1)).getTablename());
            this.tCoreMaskingDetailrecordDao.save(detail);
            TCoreMaskingTable stable = (TCoreMaskingTable)this.tCoreMaskingtableDao.queryUnique(new Criterion[]{Restrictions.eq("datadirection", "0"), Restrictions.eq("mappingkey", mappingkey), Restrictions.eq("taskid", task.getId())});
            TCoreMaskingTable ttable = (TCoreMaskingTable)this.tCoreMaskingtableDao.queryUnique(new Criterion[]{Restrictions.eq("datadirection", "1"), Restrictions.eq("mappingkey", mappingkey), Restrictions.eq("taskid", task.getId())});
            TCoreSyncKeyindex sync = new TCoreSyncKeyindex();
            sync.setTasktableid(stable.getTablename());
            sync.setTaskid(task.getId());
            if ("true".equalsIgnoreCase(task.getIsprimary())) {
               Connection srcconn = this.getConnectionByDataSystemId(stable.getDatasystemid());
               Connection tarconn = this.getConnectionByDataSystemId(ttable.getDatasystemid());
               sync.setKeystarttime(new Date());
               JdbcTool.synchronizePrimaryKey(srcconn, stable.getDbschema(), stable.getTablename(), tarconn, ttable.getDbschema(), ttable.getTablename());
               sync.setKeyendtime(new Date());
               JdbcTool.closeConnection(srcconn);
               JdbcTool.closeConnection(tarconn);
            }

            if ("true".equalsIgnoreCase(task.getIsindex())) {
               Connection srcconn = this.getConnectionByDataSystemId(stable.getDatasystemid());
               Connection tarconn = this.getConnectionByDataSystemId(ttable.getDatasystemid());
               sync.setIndexstarttime(new Date());
               JdbcTool.synchronizeIndex(srcconn, stable.getDbschema(), stable.getTablename(), tarconn, ttable.getDbschema(), ttable.getTablename());
               sync.setIndexendtime(new Date());
               JdbcTool.closeConnection(srcconn);
               JdbcTool.closeConnection(tarconn);
            }

            this.tCoreSyncKeyindexDao.save(sync);
            if ("SUCCEEDED".equals(sessionBean.getStatus())) {
               temporay.setFlag("1");
            } else if ("FAILED".equals(sessionBean.getStatus())) {
               temporay.setFlag("2");
            }

            this.tCoreMonitorTemporaryDao.saveOrUpdate(temporay);
            return;
         }

         if ("SUCCEED".equals(sessionBean.getStatus())) {
            return;
         }

         this.quartzDB(task, engine, name, userid, mappingkey, temporay);
      } catch (Exception e) {
         e.printStackTrace();
      }

   }

   @Async
   public void quartz(TCoreMaskingTask task, InfoProperty engine, String name, String userid, TCoreMonitorTemporary temporay) {
      try {
         Thread.sleep(5000L);
         SessionBean sessionBean = this.runlog(task, engine, name);
         String path = engine.getXmldir() + File.separator + "masking_task" + File.separator + task.getTaskname() + File.separator;
         if (!"SUCCEED".equals(sessionBean.getStatus()) && !"RUNNING".equals(sessionBean.getStatus()) && !"".equals(sessionBean.getStatus()) && sessionBean.getStatus() != null) {
            TCoreMaskingTaskrecord record = new TCoreMaskingTaskrecord();
            record.setTaketime(new Date());
            record.setTaskid(task.getId());
            record.setUserid(userid);
            record.setExeresult(sessionBean.getStatus());
            this.tCoreMaskingTaskrecordDao.save(record);
            TCoreMaskingDetailrecord detail = new TCoreMaskingDetailrecord();
            detail.setSuccessrow(String.valueOf(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getApplied_rows()));
            detail.setFailurerow(String.valueOf(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getRejected_rows()));
            detail.setTaskrecordid(record.getId());
            detail.setStarttime(sessionBean.getStart_time());
            detail.setEndtime(sessionBean.getEnd_time());
            detail.setSourceid(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getTablename());
            detail.setTargetid(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(1)).getTablename());
            this.tCoreMaskingDetailrecordDao.save(detail);
            if ("SUCCEEDED".equals(sessionBean.getStatus())) {
               temporay.setFlag("1");
            } else if ("FAILED".equals(sessionBean.getStatus())) {
               temporay.setFlag("2");
            }

            this.tCoreMonitorTemporaryDao.saveOrUpdate(temporay);
            File file = new File(path + name + ".pipe");
            if (file.exists()) {
               file.delete();
            }

            return;
         }

         if ("SUCCEED".equals(sessionBean.getStatus())) {
            File file = new File(path + name + ".pipe");
            if (file.exists()) {
               file.delete();
            }

            return;
         }

         this.quartz(task, engine, name, userid, temporay);
      } catch (Exception e) {
         e.printStackTrace();
      }

   }

   @Async
   public void quartzimp(TCoreMaskingTask task, InfoProperty engine, TCoreImporttask timptask, String userid) {
      SessionBean sessionBean = this.runimplog(task, engine, timptask);
      if (!"RUNNING".equals(sessionBean.getStatus()) && !"".equals(sessionBean.getStatus()) && sessionBean.getStatus() != null) {
         TCoreMaskingTaskrecord record = new TCoreMaskingTaskrecord();
         record.setTaketime(new Date());
         record.setTaskid(task.getId());
         record.setUserid(userid);
         record.setExeresult(sessionBean.getStatus());
         this.tCoreMaskingTaskrecordDao.save(record);
         TCoreMaskingDetailrecord detail = new TCoreMaskingDetailrecord();
         detail.setSuccessrow(String.valueOf(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getApplied_rows()));
         detail.setFailurerow(String.valueOf(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getRejected_rows()));
         detail.setTaskrecordid(record.getId());
         detail.setStarttime(sessionBean.getStart_time());
         detail.setEndtime(sessionBean.getEnd_time());
         detail.setSourceid(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getTablename());
         detail.setTargetid(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(1)).getTablename());
         this.tCoreMaskingDetailrecordDao.save(detail);
      } else {
         this.quartzimp(task, engine, timptask, userid);
      }
   }

   @Async
   public void quartzsub(TCoreMaskingTask task, InfoProperty engine, String name, String userid) {
      try {
         Thread.sleep(5000L);
         SessionBean sessionBean = this.runlogsub(task, engine, task.getTaskname());
         if (!"SUCCEED".equals(sessionBean.getStatus()) && !"RUNNING".equals(sessionBean.getStatus()) && !"".equals(sessionBean.getStatus()) && sessionBean.getStatus() != null) {
            TCoreMaskingTaskrecord record = new TCoreMaskingTaskrecord();
            record.setTaketime(new Date());
            record.setTaskid(task.getId());
            record.setUserid(userid);
            record.setExeresult(sessionBean.getStatus());
            this.tCoreMaskingTaskrecordDao.save(record);
            TCoreMaskingDetailrecord detail = new TCoreMaskingDetailrecord();
            detail.setSuccessrow(String.valueOf(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getApplied_rows()));
            detail.setFailurerow(String.valueOf(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getRejected_rows()));
            detail.setTaskrecordid(record.getId());
            detail.setStarttime(sessionBean.getStart_time());
            detail.setEndtime(sessionBean.getEnd_time());
            detail.setSourceid(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getTablename());
            detail.setTargetid(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(1)).getTablename());
            this.tCoreMaskingDetailrecordDao.save(detail);
            return;
         }

         if ("SUCCEED".equals(sessionBean.getStatus())) {
            return;
         }

         this.quartzsub(task, engine, name, userid);
      } catch (Exception e) {
         e.printStackTrace();
      }

   }

   @Async
   public void quartzself(TCoreMaskingselfTask task, InfoProperty engine, String name, String userid) {
      SessionBean sessionBean = this.runselflog(task, engine, name);
      if (!"RUNNING".equals(sessionBean.getStatus()) && !"".equals(sessionBean.getStatus()) && sessionBean.getStatus() != null) {
         TCoreMaskingTaskrecord record = new TCoreMaskingTaskrecord();
         record.setTaketime(new Date());
         record.setTaskid(task.getId());
         record.setUserid(userid);
         record.setExeresult(sessionBean.getStatus());
         this.tCoreMaskingTaskrecordDao.save(record);
         TCoreMaskingDetailrecord detail = new TCoreMaskingDetailrecord();
         detail.setSuccessrow(String.valueOf(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getApplied_rows()));
         detail.setFailurerow(String.valueOf(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getRejected_rows()));
         detail.setTaskrecordid(record.getId());
         detail.setStarttime(sessionBean.getStart_time());
         detail.setEndtime(sessionBean.getEnd_time());
         detail.setSourceid(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getTablename());
         detail.setTargetid(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(1)).getTablename());
         this.tCoreMaskingDetailrecordDao.save(detail);
      } else {
         this.quartzself(task, engine, name, userid);
      }
   }

   @Async
   public SessionBean runselflog(TCoreMaskingselfTask task, InfoProperty engine, String name) {
      SessionBean sessionBean = this.allwaysMonitorService.getLogForSelfTaskMapping(task, engine, name);
      return sessionBean;
   }

   @Async
   public SessionBean runlogsub(TCoreMaskingTask task, InfoProperty engine, String name) {
      SessionBean sessionBean = this.allwaysMonitorService.getLogForTaskMapping(task, engine, task.getTaskname());
      return sessionBean;
   }

   @Async
   public SessionBean runimplog(TCoreMaskingTask task, InfoProperty engine, TCoreImporttask timptask) {
      SessionBean sessionBean = this.allwaysMonitorService.getLogForImpMapping(task, engine, timptask);
      return sessionBean;
   }

   @Async
   public SessionBean runlog(TCoreMaskingTask task, InfoProperty engine, String name) {
      SessionBean sessionBean = this.allwaysMonitorService.getLogForTaskMapping(task, engine, name);
      return sessionBean;
   }

   public Connection getConnectionByDataSystemId(String datasystemid) {
      TCoreDatasystem datasystem = (TCoreDatasystem)this.tCoreDatasystemDao.get(datasystemid);
      String dbcode = datasystem.getDbtype();
      String ip = datasystem.getDbip();
      String port = datasystem.getDbport();
      String servername = datasystem.getDbservername();
      String server = datasystem.getServername();
      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:
            url = EdbType.getUrlByEdbcode(dbcode, ip, port, servername);
      }

      String username = datasystem.getUsername();
      String password = "1".equals(datasystem.getFlag()) ? AesTool.decrypt(datasystem.getPassword(), "ghca") : datasystem.getPassword();
      String driver = EdbType.getEdbTypeByDbcode(dbcode).getDbdriver();
      Connection conn = JdbcTool.getConnection(driver, url, username, password);
      return conn;
   }

   @Async
   public void updateDataConut(TCoreMaskingTable table, TCoreMonitorTemporary temporay) {
      Connection conn = this.getConnectionByDataSystemId(table.getDatasystemid());
      int count = JdbcTool.getTableDataCount(conn, table.getDbschema(), table.getTablename());
      JdbcTool.closeConnection(conn);
      temporay.setDatacount(count);
      this.tCoreMonitorTemporaryDao.update(temporay);
   }

   @Async
   public void control(String taskid, String userid) throws Exception {
      TCoreMaskingTask task = (TCoreMaskingTask)this.tCoreMaskingtaskDao.get(taskid);
      if (task != null) {
         String flag = "";
         flag = task.getFlag();
         if (!flag.equals(EmaskingTaskType.FILE_TO_DB.getFlag()) && !flag.equals(EmaskingTaskType.FILE_TO_FILE.getFlag())) {
            this.infoService.executeTask(taskid, userid);
         } else {
            this.infoService.executeFileTask(taskid, userid);
         }
      } else {
         this.infoService.executeTask(taskid, userid);
      }

   }

   @Async
   public void sqlServerBcpExecute(InfoProperty engine, TCoreMaskingTask task, HashMap<String, TCoreMaskingTable> sourceTableMaps, String errorLog, TCoreMaskingTable tCoreMaskingTable) {
      String completeStatus = this.workflowTaskCompleteMonitor(engine, task.getFdname(), ((TCoreMaskingTable)sourceTableMaps.get(tCoreMaskingTable.getMappingkey())).getTablename());
      if ("1".equals(completeStatus)) {
         CommandTool.command("/data/infa_sqlserver/" + task.getTaskname() + "/" + ((TCoreMaskingTable)sourceTableMaps.get(tCoreMaskingTable.getMappingkey())).getTablename() + ".sh");
      }

   }

   @Async
   public void quartzSqlServerFileTask(TCoreMaskingTask task, InfoProperty engine, String name, String userid, TCoreMonitorTemporary temporay, Map<String, String> map) {
      try {
         Thread.sleep(5000L);
         String completeStatus = this.workflowTaskCompleteMonitor(engine, task.getFdname(), name);
         String filepath = (String)map.get("filepath");
         String filename = (String)map.get("filename");
         String type = (String)map.get("type");
         File file = new File(filepath + filename);
         File file_source = new File(filepath + "w" + filename);
         if ("1".equals(completeStatus)) {
            CommandTool.command("chmod 777 -R /data/infa_sqlserver/" + task.getTaskname() + "/");
            CommandTool.command("/data/infa_sqlserver/" + task.getTaskname() + "/" + temporay.getTargetname() + ".sh");
            System.out.println(">>>>>>>>>>>>>>>>>>workflowTaskCompleteMonitorFILE:监控到脱敏任务 - workflow:【" + task.getTaskname() + "】 > folderName：【" + task.getFdname() + "】;  workflowName【 wf_" + name + "】 任务执行完成。");
            SessionBean sessionBean = this.runlog(task, engine, name);
            String path = engine.getXmldir() + File.separator + task.getTaskname() + File.separator;
            if (!"".equals(sessionBean.getStatus()) && sessionBean.getStatus() != null) {
               TCoreMaskingTaskrecord record = new TCoreMaskingTaskrecord();
               record.setTaketime(new Date());
               record.setTaskid(task.getId());
               record.setUserid(userid);
               record.setExeresult(sessionBean.getStatus());
               this.tCoreMaskingTaskrecordDao.save(record);
               TCoreMaskingDetailrecord detail = new TCoreMaskingDetailrecord();
               detail.setSuccessrow(String.valueOf(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getApplied_rows()));
               detail.setFailurerow(String.valueOf(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getRejected_rows()));
               detail.setTaskrecordid(record.getId());
               detail.setStarttime(sessionBean.getStart_time());
               detail.setEndtime(sessionBean.getEnd_time());
               detail.setSourceid(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(0)).getTablename());
               detail.setTargetid(((SessionBeanDetail)sessionBean.getSessionBeanDetail().get(1)).getTablename());
               this.tCoreMaskingDetailrecordDao.save(detail);
               if (type.equals("1")) {
                  String netfilepath = (String)map.get("netfilepath");
                  String netfilename = (String)map.get("netfilename");
                  String datasystenid = (String)map.get("datasystenid");
                  if (null != datasystenid) {
                     TCoreDatasystem filesystem = (TCoreDatasystem)this.tCoreDatasystemDao.get(datasystenid);
                     if (filesystem.getDbtype().equals("SFTP")) {
                        String username = filesystem.getUsername();
                        String password = filesystem.getPassword();
                        String host = filesystem.getDbip();
                        Integer port = Integer.parseInt(filesystem.getDbport());
                        SFTPUtil sftp = new SFTPUtil(username, password, host, port);
                        SFTPUtil.login();
                        InputStream is = new FileInputStream(file);
                        sftp.upload(netfilepath, netfilename, is);
                        is.close();
                        sftp.logout();
                     } else if (filesystem.getDbtype().equals("FTP")) {
                        String username = filesystem.getUsername();
                        String password = filesystem.getPassword();
                        String host = filesystem.getDbip();
                        Integer port = Integer.parseInt(filesystem.getDbport());
                        InputStream is = new FileInputStream(file);
                        FtpTool.uploadFile(host, port, username, password, netfilepath, netfilename, is);
                        is.close();
                     }
                  }
               }

               if ("SUCCEEDED".equals(sessionBean.getStatus())) {
                  temporay.setFlag("1");
               } else if ("FAILED".equals(sessionBean.getStatus())) {
                  temporay.setFlag("2");
               }

               this.tCoreMonitorTemporaryDao.saveOrUpdate(temporay);
            }
         }

         if (file.exists()) {
            file.delete();
         }

         if (file_source.exists()) {
            file_source.delete();
         }
      } catch (Exception e) {
         e.printStackTrace();
      }

   }
}
