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

import com.chenyang.nse.bussiness.config.PropertiesLoaderUtils;
import com.chenyang.nse.bussiness.dao.PageInfo;
import com.chenyang.nse.bussiness.dao.table.core.scheduler.TCoreSchedulerKmRulesDao;
import com.chenyang.nse.bussiness.dao.table.core.scheduler.TCoreSchedulerRelationDao;
import com.chenyang.nse.bussiness.dao.table.core.scheduler.TCoreSchedulerRulesDao;
import com.chenyang.nse.bussiness.engine.infa.InfoProperty;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystem;
import com.chenyang.nse.bussiness.entity.orm.table.core.desensitizationtask.DesensitizationFile;
import com.chenyang.nse.bussiness.entity.orm.table.core.desensitizationtask.DesensitizationMonitor;
import com.chenyang.nse.bussiness.entity.orm.table.core.desensitizationtask.DesensitizationTable;
import com.chenyang.nse.bussiness.entity.orm.table.core.desensitizationtask.Desensitizationsource;
import com.chenyang.nse.bussiness.entity.orm.table.core.desensitizationtask.Desensitizationtarget;
import com.chenyang.nse.bussiness.entity.orm.table.core.desensitizationtask.Desensitizationtask;
import com.chenyang.nse.bussiness.entity.orm.table.core.scheduler.TCoreSchedulerKmRules;
import com.chenyang.nse.bussiness.entity.orm.table.core.scheduler.TCoreSchedulerRelation;
import com.chenyang.nse.bussiness.entity.orm.table.core.scheduler.TCoreSchedulerRules;
import com.chenyang.nse.bussiness.entity.param.scheduler.AddSchedulerParam;
import com.chenyang.nse.bussiness.entity.param.scheduler.SaveTaskParam;
import com.chenyang.nse.bussiness.entity.vo.ResultVO;
import com.chenyang.nse.bussiness.entity.vo.scheduler.RulesVO;
import com.chenyang.nse.bussiness.job.DelefolderTaskJob;
import com.chenyang.nse.bussiness.job.GenerateTicketTaskJob;
import com.chenyang.nse.bussiness.job.MaskingTaskJob;
import com.chenyang.nse.bussiness.job.MaskingTaskKmJob;
import com.chenyang.nse.bussiness.job.TaskScheduleModel;
import com.chenyang.nse.bussiness.service.core.DataSystemService;
import com.chenyang.nse.bussiness.service.core.DesensitizationtaskSerialService;
import com.chenyang.nse.bussiness.service.core.DesensitizationtaskService;
import com.chenyang.nse.bussiness.service.core.SchedulerService;
import com.chenyang.nse.bussiness.thread.ExecuteParam;
import com.chenyang.nse.bussiness.tools.jdbc.JdbcTool;
import com.chenyang.nse.bussiness.tools.quartz.CronUtils;
import com.chenyang.nse.bussiness.tools.quartz.QuartzUtil;
import com.chenyang.nse.bussiness.tools.ticket.TicketTool;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service
@Transactional
public class SchedulerServiceImpl implements SchedulerService {
   private static final Logger logger = LoggerFactory.getLogger(SchedulerServiceImpl.class);
   public static final String DB_pwc_FILE_batchwrite_DB = "DBtoDB,normal,batchwrite";
   public static final String DB_batchread_FILE_pwc_DB = "DBtoDB,batchread,normal";
   public static final String DB_batchread_FILE_pwc_FILE_batchwrite_DB = "DBtoDB,batchread,batchwrite";
   public static final String DB_pwc_DB = "DBtoDB,normal,normal";
   public static final String DB_pwc_FILE = "DBtoFILE,normal";
   public static final String DB_batchread_FILE_pwc_FILE = "DBtoFILE,batchread";
   public static final String FILE_pwc_FILE_batchwrite_DB = "FILEtoDB,batchwrite";
   public static final String FILE_pwc_DB = "FILEtoDB,normal";
   public static final String FILE_pwc_FILE = "FILEtoFILE";
   public static final String HIVE_batchread_FILE_pwc_FILE_batchwrite_HIVE = "HIVEtoHIVE,batchread,batchwrite";
   @Autowired
   private TCoreSchedulerKmRulesDao tCoreSchedulerKmRulesDao;
   @Autowired
   private TCoreSchedulerRulesDao tCoreSchedulerRulesDao;
   @Autowired
   private TCoreSchedulerRelationDao tCoreSchedulerRelationDao;
   @Autowired
   private DesensitizationtaskService desensitizationtaskService;
   @Autowired
   private DesensitizationtaskSerialService desensitizationtaskSerialService;
   @Autowired
   private DataSystemService dataSystemService;

   public String saveSchedualTask(TCoreSchedulerKmRules schedulerRule) throws ParseException {
      String result = "true";
      if (null != schedulerRule.getId() && !"".equals(schedulerRule.getId())) {
         List<TCoreSchedulerKmRules> ruleList = this.tCoreSchedulerKmRulesDao.queryAll(new Criterion[]{Restrictions.ne("id", schedulerRule.getId())});
         if (null != ruleList && ruleList.size() > 0) {
            result = "轮巡任务已存在，请求id错误，不能修改！";
            return result;
         }

         schedulerRule.setUpdatetime(new Date());
         this.tCoreSchedulerKmRulesDao.update(schedulerRule);
      } else {
         schedulerRule.setId(UUID.randomUUID().toString().replace("-", ""));
         schedulerRule.setCreatetime(new Date());
         this.tCoreSchedulerKmRulesDao.save(schedulerRule);
      }

      TriggerKey triggerKey = new TriggerKey(schedulerRule.getId());
      JobKey jobKey = new JobKey(schedulerRule.getId() + "job");
      if ("1".equals(schedulerRule.getRulevalidity())) {
         TCoreSchedulerKmRules rules = (TCoreSchedulerKmRules)this.tCoreSchedulerKmRulesDao.queryUnique(new Criterion[]{Restrictions.eq("id", schedulerRule.getId())});

         try {
            QuartzUtil.removeJob(jobKey);
            QuartzUtil.removeTrigger(triggerKey);
         } catch (SchedulerException e) {
            e.printStackTrace();
         }

         JobDataMap jobDataMap = new JobDataMap();
         jobDataMap.put("rulesType", rules.getRulestype());
         jobDataMap.put("schedulerId", schedulerRule.getId());
         String cronExpression = "";
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         if (rules.getRulestype().equals("0")) {
            String rulestime = rules.getRulestime();
            Date parse = sdf.parse(rulestime);
            if (parse.before(new Date())) {
               result = "调度规则过期，无法启动！";
               return result;
            }

            cronExpression = CronUtils.getCron(parse);
         } else if (null != rules.getRulestime() && !"".equals(rules.getRulestime())) {
            TaskScheduleModel t = new TaskScheduleModel();
            String rulestime = rules.getRulestime();
            String[] arr = rulestime.split(":");
            t.setHour(Integer.valueOf(arr[0]));
            t.setMinute(Integer.valueOf(arr[1]));
            t.setSecond(Integer.valueOf(arr[2]));
            if (rules.getHowtime().equals("")) {
               t.setJobType(1);
               cronExpression = CronUtils.createCronExpression(t);
            } else {
               t.setJobType(3);
               String[] arr1 = rules.getHowtime().split(",");
               Integer[] dayOfWeeks = new Integer[arr1.length];

               for(int i = 0; i < arr1.length; ++i) {
                  dayOfWeeks[i] = Integer.valueOf(arr1[i]);
               }

               t.setDayOfWeeks(dayOfWeeks);
               cronExpression = CronUtils.createCronExpression(t);
            }
         }

         if (null != schedulerRule.getRulesminute() && !"".equals(schedulerRule.getRulesminute())) {
            cronExpression = "0 0/" + schedulerRule.getRulesminute() + " * * * ?";
         } else if (null != schedulerRule.getRuleshour() && !"".equals(schedulerRule.getRuleshour())) {
            cronExpression = "0 0 0/" + schedulerRule.getRuleshour() + " * * ?";
         } else if (null != schedulerRule.getRulesday() && !"".equals(schedulerRule.getRulesday())) {
            cronExpression = "0 0 0 1/" + schedulerRule.getRulesday() + " * ?";
         }

         try {
            QuartzUtil.addJob(MaskingTaskKmJob.class, cronExpression, jobKey, triggerKey, jobDataMap);
            TCoreSchedulerKmRules tCoreSchedulerKmRules = (TCoreSchedulerKmRules)this.tCoreSchedulerKmRulesDao.get(schedulerRule.getId());
            tCoreSchedulerKmRules.setRulevalidity("1");
            this.tCoreSchedulerKmRulesDao.update(tCoreSchedulerKmRules);
         } catch (SchedulerException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            result = e.getMessage();
            return result;
         } catch (ParseException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            result = e.getMessage();
            return result;
         }
      } else {
         if (!"0".equals(schedulerRule.getRulevalidity())) {
            result = "启用轮询参数错误!";
            return result;
         }

         try {
            QuartzUtil.removeJob(jobKey);
            QuartzUtil.removeTrigger(triggerKey);
         } catch (SchedulerException e) {
            e.printStackTrace();
         }
      }

      return result;
   }

   public List<Desensitizationtask> getAddUnSaveTask(String projectid, String srname) {
      return this.tCoreSchedulerRulesDao.getAddUnSaveTask(projectid, srname);
   }

   public List<Desensitizationtask> getEditUnSaveTask(String id, String projectid, String srname) {
      return this.tCoreSchedulerRulesDao.getEditUnSaveTask(id, projectid, srname);
   }

   public ResultVO saveSchedulerTask(AddSchedulerParam asp) {
      ResultVO rv = new ResultVO("error", false);
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      StringBuffer sbf = new StringBuffer();

      for(SaveTaskParam stp : asp.getSaveTask()) {
         sbf.append("'");
         sbf.append(stp.getId());
         sbf.append("'");
         sbf.append(",");
      }

      sbf.deleteCharAt(sbf.length() - 1);
      long tablenum = this.desensitizationtaskService.getTableNumByAll(sbf.toString());
      Properties props = new Properties();

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

      long num_thread = new Long(props.getProperty("threadPool.queueCapacity"));
      if (num_thread < tablenum) {
         rv.setMessage("error");
         rv.setResult(false);
         return rv;
      } else {
         try {
            Boolean isEdit = false;
            TCoreSchedulerRules rules = new TCoreSchedulerRules();
            if (asp.getId() != "" && asp.getId() != null) {
               isEdit = true;
            }

            if (isEdit) {
               rules.setId(asp.getId());
            }

            rules.setSrname(asp.getSrName());
            rules.setRulestype(asp.getRulesType());
            rules.setRulestime(asp.getRulestime());
            rules.setExpression(QuartzUtil.getCronExpression(asp.getRulesType(), asp.getRulesDay(), asp.getRulesHour(), asp.getRulesMinute(), asp.getXloptions(), asp.getHowtime()));
            rules.setCreatetime(asp.getCreateTime().equals("") ? new Date() : sdf.parse(asp.getCreateTime()));
            rules.setUpdatetime(new Date());
            rules.setRulevalidity(asp.getRuleValidity());
            rules.setProjectid(asp.getProjectid());
            this.tCoreSchedulerRulesDao.saveOrUpdate(rules);
            if (isEdit) {
               this.tCoreSchedulerRelationDao.remove(new Criterion[]{Restrictions.eq("rulesid", rules.getId())});
            }

            List<String> idList = new ArrayList();

            for(SaveTaskParam stp : asp.getSaveTask()) {
               TCoreSchedulerRelation relation = new TCoreSchedulerRelation();
               relation.setRulesid(rules.getId());
               relation.setTaskid(stp.getId());
               relation.setTaskname(stp.getTaskname());
               relation.setCreatetime(new Date());
               relation.setUpdatetime(new Date());
               this.tCoreSchedulerRelationDao.saveOrUpdate(relation);
               idList.add(stp.getId());
            }

            TriggerKey triggerKey = new TriggerKey(rules.getId());
            JobKey jobKey = new JobKey(rules.getId() + "job");
            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("idList", idList);
            jobDataMap.put("rulesType", rules.getRulestype());
            jobDataMap.put("schedulerId", rules.getId());
            if (isEdit) {
               QuartzUtil.removeJob(jobKey);
               QuartzUtil.removeTrigger(triggerKey);
            }

            QuartzUtil.addJob(MaskingTaskJob.class, rules.getExpression(), jobKey, triggerKey, jobDataMap);
            rv.setMessage("success");
            rv.setResult(true);
            return rv;
         } catch (SchedulerException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return rv;
         } catch (ParseException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return rv;
         }
      }
   }

   @Transactional
   public ResultVO saveNewSchedulerTask(AddSchedulerParam asp) {
      ResultVO rv = new ResultVO("error", false);
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date date = new Date();
      StringBuffer sbf = new StringBuffer();

      for(SaveTaskParam stp : asp.getSaveTask()) {
         sbf.append("'");
         sbf.append(stp.getId());
         sbf.append("'");
         sbf.append(",");
      }

      sbf.deleteCharAt(sbf.length() - 1);
      long tablenum = this.desensitizationtaskService.getTableNumByAll(sbf.toString());
      Properties props = new Properties();

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

      long num_thread = new Long(props.getProperty("threadPool.queueCapacity"));
      if (num_thread < tablenum) {
         rv.setMessage("error");
         rv.setResult(false);
         return rv;
      } else {
         try {
            Boolean isEdit = false;
            TCoreSchedulerRules rules = new TCoreSchedulerRules();
            if (asp.getId() != "" && asp.getId() != null) {
               isEdit = true;
            }

            if (isEdit) {
               rules.setId(asp.getId());
            }

            rules.setSrname(asp.getSrName());
            rules.setRulestype(asp.getRulesType());
            if (!"天".equals(asp.getXloptions()) && !"1".equals(asp.getXloptions())) {
               rules.setXloptions(asp.getXloptions());
            } else {
               rules.setXloptions("1");
            }

            rules.setHowtime(asp.getHowtime());
            rules.setRulesday(asp.getRulesDay());
            rules.setRuleshour(asp.getRulesHour());
            rules.setRulesminute(asp.getRulesMinute());
            rules.setRulestime(asp.getTimebox());
            rules.setTimebox(asp.getTimebox());
            rules.setErrormessage("");
            rules.setExpression(QuartzUtil.getCronExpression(asp.getRulesType(), asp.getRulesDay(), asp.getRulesHour(), asp.getRulesMinute(), asp.getXloptions(), asp.getHowtime()));
            rules.setUpdatetime(new Date());
            rules.setRulevalidity(asp.getRuleValidity());
            rules.setProjectid(asp.getProjectid());
            rules.setId(asp.getId());
            if (asp.getId() != null && !"".equals(asp.getId())) {
               String date1 = sdf.format(date);
               this.tCoreSchedulerRulesDao.schedulerUpdate(rules, date1);
            } else {
               rules.setCreatetime(new Date());
               this.tCoreSchedulerRulesDao.save(rules);
            }

            if (isEdit) {
               this.tCoreSchedulerRelationDao.remove(new Criterion[]{Restrictions.eq("rulesid", rules.getId())});
            }

            List<String> idList = new ArrayList();

            for(SaveTaskParam stp : asp.getSaveTask()) {
               TCoreSchedulerRelation relation = new TCoreSchedulerRelation();
               relation.setRulesid(rules.getId());
               relation.setTaskid(stp.getId());
               relation.setTaskname(stp.getTaskname());
               relation.setCreatetime(new Date());
               relation.setUpdatetime(new Date());
               this.tCoreSchedulerRelationDao.saveOrUpdate(relation);
               idList.add(stp.getId());
            }

            TriggerKey triggerKey = new TriggerKey(rules.getId());
            JobKey jobKey = new JobKey(rules.getId() + "job");
            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("idList", idList);
            jobDataMap.put("rulesType", rules.getRulestype());
            jobDataMap.put("schedulerId", rules.getId());
            if (isEdit) {
               QuartzUtil.removeJob(jobKey);
               QuartzUtil.removeTrigger(triggerKey);
            }

            QuartzUtil.addJob(MaskingTaskJob.class, rules.getExpression(), jobKey, triggerKey, jobDataMap);
            rv.setMessage("success");
            rv.setResult(true);
            return rv;
         } catch (SchedulerException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return rv;
         } catch (ParseException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return rv;
         }
      }
   }

   public List<RulesVO> getSchedulerTable(PageInfo pageinfo, String projectid) {
      List<RulesVO> rulesVoList = new ArrayList();
      List<Map<String, Object>> rulesList = this.tCoreSchedulerRulesDao.queryDispatchByProjectid(pageinfo, projectid);
      if (rulesList != null && !rulesList.isEmpty()) {
         for(int i = 0; i < rulesList.size(); ++i) {
            RulesVO rv = new RulesVO();
            rv.setId((String)((Map)rulesList.get(i)).get("id"));
            rv.setCreatetime((Date)((Map)rulesList.get(i)).get("createtime"));
            rv.setExpression((String)((Map)rulesList.get(i)).get("expression"));
            rv.setTimebox((String)((Map)rulesList.get(i)).get("timebox"));
            rv.setXloptions((String)((Map)rulesList.get(i)).get("xloptions"));
            rv.setHowtime((String)((Map)rulesList.get(i)).get("howtime"));
            rv.setXloptions((String)((Map)rulesList.get(i)).get("xloptions"));
            rv.setRuleshour((String)((Map)rulesList.get(i)).get("ruleshour"));
            rv.setRulesminute((String)((Map)rulesList.get(i)).get("rulesminute"));
            rv.setRulestype((String)((Map)rulesList.get(i)).get("rulestype"));
            rv.setRulevalidity((String)((Map)rulesList.get(i)).get("rulevalidity"));
            rv.setSrname((String)((Map)rulesList.get(i)).get("srname"));
            rv.setErrormessage((String)((Map)rulesList.get(i)).get("errormessage"));
            List<TCoreSchedulerRelation> relationList = this.tCoreSchedulerRelationDao.queryAll(new Criterion[]{Restrictions.eq("rulesid", ((Map)rulesList.get(i)).get("id"))});
            rv.setRelation(relationList);
            rulesVoList.add(rv);
         }
      }

      return rulesVoList;
   }

   public void removeSchedulerTask(String rulesid) {
      TriggerKey triggerKey = new TriggerKey(rulesid);

      try {
         QuartzUtil.removeTrigger(triggerKey);
      } catch (SchedulerException e) {
         e.printStackTrace();
      }

      this.tCoreSchedulerRelationDao.remove(new Criterion[]{Restrictions.eq("rulesid", rulesid)});
      this.tCoreSchedulerRulesDao.removeById(rulesid);
   }

   public void initProjectStart() {
      try {
         for(TCoreSchedulerRules item : this.tCoreSchedulerRulesDao.queryAll()) {
            TriggerKey triggerKey = new TriggerKey(item.getId());
            JobKey jobKey = new JobKey(item.getId() + "job");
            JobDataMap jobDataMap = new JobDataMap();
            List<String> idList = new ArrayList();

            for(TCoreSchedulerRelation relationItem : this.tCoreSchedulerRelationDao.queryAll(new Criterion[]{Restrictions.eq("rulesid", item.getId())})) {
               idList.add(relationItem.getTaskid());
            }

            jobDataMap.put("idList", idList);
            jobDataMap.put("rulesType", item.getRulestype());
            jobDataMap.put("schedulerId", item.getId());
            if (item.getRulestype().equals("0") && !QuartzUtil.compareNowDate(item.getRulesday(), item.getRuleshour(), item.getRulesminute())) {
               if (item.getRulevalidity().equals("0")) {
                  this.modifyRuleValidity(item.getId(), false);
               }
            } else {
               QuartzUtil.addJob(MaskingTaskJob.class, item.getExpression(), jobKey, triggerKey, jobDataMap);
            }
         }
      } catch (ParseException e) {
         e.printStackTrace();
         logger.error("单次调度任务比较时间时，转换时间报错！");
      } catch (SchedulerException e) {
         e.printStackTrace();
         logger.error("创建调度任务报错！");
      }

   }

   public void initDeletefileStart() {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      System.out.println("====================contextInitialized=======================");
      AddSchedulerParam asp = new AddSchedulerParam();
      asp.setCreateTime("");
      asp.setRulesDay("0");
      asp.setRulesHour("00");
      asp.setRulesMinute("00");
      asp.setRulesType("1");
      asp.setRuleValidity("0");
      asp.setSrName("rw");
      TCoreSchedulerRules rules = new TCoreSchedulerRules();
      Boolean isEdit = false;
      if (asp.getId() != "" && asp.getId() != null) {
         isEdit = true;
      }

      if (isEdit) {
         rules.setId(asp.getId());
      }

      rules.setId("1");
      rules.setSrname(asp.getSrName());
      rules.setRulestype(asp.getRulesType());
      rules.setRulesday(asp.getRulesDay());
      rules.setRuleshour(asp.getRulesHour());
      rules.setRulesminute(asp.getRulesMinute());
      rules.setExpression(QuartzUtil.getCronExpression(asp.getRulesType(), asp.getRulesDay(), asp.getRulesHour(), asp.getRulesMinute(), asp.getXloptions(), asp.getHowtime()));

      try {
         rules.setCreatetime(asp.getCreateTime().equals("") ? new Date() : sdf.parse(asp.getCreateTime()));
      } catch (ParseException e) {
         e.printStackTrace();
      }

      rules.setUpdatetime(new Date());
      rules.setRulevalidity(asp.getRuleValidity());
      TriggerKey triggerKey = new TriggerKey(rules.getId());
      JobKey jobKey = new JobKey(rules.getId() + "job");
      JobDataMap jobDataMap = new JobDataMap();
      jobDataMap.put("rulesType", rules.getRulestype());
      jobDataMap.put("schedulerId", rules.getId());

      try {
         QuartzUtil.addJob(DelefolderTaskJob.class, rules.getExpression(), jobKey, triggerKey, jobDataMap);
      } catch (SchedulerException e) {
         e.printStackTrace();
      } catch (ParseException e) {
         e.printStackTrace();
      }

   }

   public ResultVO repeatTaskName(String srName) {
      ResultVO rv = new ResultVO("success", true);
      List<TCoreSchedulerRules> rules = this.tCoreSchedulerRulesDao.queryAll(new Criterion[]{Restrictions.eq("srname", srName)});
      if (rules.isEmpty()) {
         rv.setMessage("error");
         rv.setResult(false);
      }

      return rv;
   }

   public List<TCoreSchedulerRules> repeatTaskName1(String srName, String projectid) {
      List<TCoreSchedulerRules> rules = this.tCoreSchedulerRulesDao.repeatTaskName1(srName, projectid);
      return rules;
   }

   public void modifyRuleValidity(String schedulerRuleId, Boolean isRemove) {
      TCoreSchedulerRules tCoreSchedulerRules = (TCoreSchedulerRules)this.tCoreSchedulerRulesDao.get(schedulerRuleId);
      if (isRemove) {
         List<TCoreSchedulerRelation> relationList = this.tCoreSchedulerRelationDao.queryAll(new Criterion[]{Restrictions.eq("rulesid", schedulerRuleId)});
         if (relationList.size() == 1) {
            tCoreSchedulerRules.setRulevalidity("1");
         }
      } else {
         tCoreSchedulerRules.setRulevalidity("1");
      }

      this.tCoreSchedulerRulesDao.update(tCoreSchedulerRules);
   }

   public void removeSchedulerRelationByMaskingId(String maskingId) {
      for(TCoreSchedulerRelation item : this.tCoreSchedulerRelationDao.queryAll(new Criterion[]{Restrictions.eq("taskid", maskingId)})) {
         this.modifyRuleValidity(item.getRulesid(), true);
      }

      this.tCoreSchedulerRelationDao.remove(new Criterion[]{Restrictions.eq("taskid", maskingId)});
   }

   public void executeTask(String taskid, String schedulerId) throws Exception {
      String masking_engine_type = "";

      try {
         Desensitizationsource desensitizationsource = this.desensitizationtaskService.querySourceInfo(taskid);
         Desensitizationtarget desensitizationtarget = this.desensitizationtaskService.queryTargetById(taskid);
         Desensitizationtask desensitizationtask = this.desensitizationtaskService.queryTaskById(taskid);
         DesensitizationFile desensitizationFile = this.desensitizationtaskService.queryDesensitizationfileBytaskid(taskid);
         boolean isOracleTodmp = false;
         if (null != desensitizationsource && desensitizationsource.getDatasourceid() != null && !"".equals(desensitizationsource.getDatasourceid()) && "oracledmp".equals(desensitizationtarget.getExecution_type())) {
            isOracleTodmp = true;
         }

         masking_engine_type = PropertiesLoaderUtils.loadAllProperties("config.properties").getProperty("masking_engine_type");
         TCoreDatasystem tCoreDatasystemSource = new TCoreDatasystem();
         TCoreDatasystem tCoreDatasystemTarget = new TCoreDatasystem();
         if (null != desensitizationsource && desensitizationsource.getDatasourceid() != null && !"".equals(desensitizationsource.getDatasourceid()) && !isOracleTodmp) {
            tCoreDatasystemSource = this.dataSystemService.queryDataSystemById(desensitizationsource.getDatasourceid());
         } else if (null == desensitizationsource || !"1".equals(desensitizationsource.getIsdmpfile()) && !isOracleTodmp) {
            tCoreDatasystemSource.setDbtype("FILE");
         } else {
            tCoreDatasystemSource.setDbtype("ORACLE");
         }

         if (null != desensitizationtarget && desensitizationtarget.getDatasourceid() != null && !"".equals(desensitizationtarget.getDatasourceid())) {
            tCoreDatasystemTarget = this.dataSystemService.queryDataSystemById(desensitizationtarget.getDatasourceid());
         } else if (null != desensitizationtarget && "1".equals(desensitizationtarget.getDmpimport())) {
            tCoreDatasystemTarget.setDbtype("ORACLE");
         } else {
            tCoreDatasystemTarget.setDbtype("FILE");
         }

         String type = JdbcTool.returnType(desensitizationsource.getExecution_type(), desensitizationtarget.getExecution_type(), desensitizationtask.getTasktype().replace("FTP", "FILE").replace("SFTP", "FILE").replace("LOCALFILE", "FILE"));
         System.out.println(type + "type");
         InfoProperty infoProperty = this.desensitizationtaskService.getInfoProperty();
         long groupId = (new Date()).getTime();
         ExecuteParam executeParam = new ExecuteParam();
         executeParam.setSourceDataSystem(tCoreDatasystemSource);
         executeParam.setTargetDataSystem(tCoreDatasystemTarget);
         executeParam.setInfoProperty(infoProperty);
         executeParam.setDataSourceId(desensitizationsource.getDatasourceid());
         executeParam.setDataTargetId(desensitizationtarget.getDatasourceid());
         executeParam.setFolderName(desensitizationtask.getFoldername());
         executeParam.setSourceSchemaName(desensitizationsource.getDataschema());
         executeParam.setTargetSchemaName(desensitizationtarget.getDataschema());
         executeParam.setIsPrimary(desensitizationtarget.getIsprimary());
         executeParam.setIsIndex(desensitizationtarget.getIsindex());
         executeParam.setTaskid(taskid);
         executeParam.setSourceFileDir(desensitizationsource.getSourcefiledir());
         executeParam.setTragetFileDir(desensitizationtarget.getTargetfiledir());
         executeParam.setTaskNameReal(desensitizationtask.getTasknamereal());
         executeParam.setSourcetype(desensitizationsource.getExecution_type());
         executeParam.setTargettype(desensitizationtarget.getExecution_type());
         executeParam.setLoadscripttype(desensitizationtarget.getLoadscripttype());
         executeParam.setTableprefix(desensitizationtask.getTableprefix());
         executeParam.setTablesuffix(desensitizationtask.getTablesuffix());
         executeParam.setDesensitizationtarget(desensitizationtarget);
         executeParam.setSourceDbType(tCoreDatasystemSource.getDbtype());
         executeParam.setTargetDbType(tCoreDatasystemTarget.getDbtype());
         executeParam.setDesensitizationFile(desensitizationFile);
         if (isOracleTodmp) {
            executeParam.setDataSourceId((String)null);
            executeParam.setSourceSchemaName((String)null);
         }

         String taskType = JdbcTool.returnTaskType(desensitizationtask.getTasktype());
         List<DesensitizationTable> tableList = this.desensitizationtaskService.queryTableList(taskid);
         Map<String, String> tableMap = new HashMap();
         StringBuilder batchInserSql = new StringBuilder();
         List<String> list_table = JdbcTool.sql_insert_q(new DesensitizationMonitor());
         list_table.add("id");
         String sqlBase = JdbcTool.sql_insert_z(list_table, "desensitization_monitor");
         batchInserSql.append(sqlBase);

         for(DesensitizationTable desensitizationTable : tableList) {
            String id = UUID.randomUUID().toString();
            tableMap.put(desensitizationTable.getTablename(), id);
            DesensitizationMonitor desensitizationMonitor = new DesensitizationMonitor();
            desensitizationMonitor.setId(id);
            desensitizationMonitor.setSourcename(desensitizationTable.getTablename());
            desensitizationMonitor.setTargetname((desensitizationtask.getTableprefix() == null ? "" : desensitizationtask.getTableprefix()) + desensitizationTable.getT_tablename() + (desensitizationtask.getTablesuffix() == null ? "" : desensitizationtask.getTablesuffix()));
            desensitizationMonitor.setRunstatus(0);
            desensitizationMonitor.setGroupid(new BigInteger(String.valueOf(groupId)));
            desensitizationMonitor.setTaskid(taskid);
            desensitizationMonitor.setTasktype(taskType);
            desensitizationMonitor.setIsimport("0");
            batchInserSql.append(JdbcTool.sql_insert_h(desensitizationMonitor, list_table));
         }

         executeParam.setTableMap(tableMap);
         executeParam.setGroupId(groupId);
         this.desensitizationtaskService.saveDesensitizationMonitor(batchInserSql.deleteCharAt(batchInserSql.length() - 1));
         new Properties();
         Properties var31 = PropertiesLoaderUtils.loadAllProperties("config.properties");
         String engineType = var31.getProperty("masking_engine_type");
         this.desensitizationtaskService.updateTask_isengine(executeParam, engineType);
         switch (type) {
            case "DBtoDB,normal,batchwrite":
               this.desensitizationtaskService.executeDB_pwc_FILE_batchwrite_DB(executeParam);
               break;
            case "FILEtoDB,batchwrite":
               this.desensitizationtaskService.executeFILE_pwc_FILE_batchwrite_DB(executeParam);
               break;
            case "DBtoDB,batchread,batchwrite":
               this.desensitizationtaskService.executeDB_batchread_FILE_pwc_FILE_batchwrite_DB(executeParam);
               break;
            case "DBtoFILE,batchread":
               this.desensitizationtaskService.executeDB_batchread_FILE_pwc_FILE(executeParam);
               break;
            case "DBtoDB,batchread,normal":
               this.desensitizationtaskService.executeDB_batchread_FILE_pwc_DB(executeParam);
               break;
            default:
               if ("oracledmp".equals(executeParam.getSourcetype())) {
                  this.desensitizationtaskService.executeDB_batchread_FILE_pwc_FILE_batchwrite_DB(executeParam);
               } else if (desensitizationtask.getTasktype().contains("HIVE")) {
                  this.desensitizationtaskService.executeTask(executeParam);
               } else {
                  if (StringUtils.isNotBlank(type)) {
                     String[] typeArr = type.split(",");
                     if (typeArr.length > 0 && null != typeArr[0]) {
                        executeParam.setDataProcessType(typeArr[0].replace("to", "_pwc_"));
                     }
                  }

                  this.desensitizationtaskService.executeTaskNormal(executeParam);
               }
         }
      } catch (Exception e) {
         e.printStackTrace();
         StringWriter sw = new StringWriter();
         PrintWriter pw = new PrintWriter(sw);
         e.printStackTrace(pw);
         this.tCoreSchedulerRulesDao.saveerror(schedulerId, sw.toString());
      }

   }

   public String generateTicket() {
      System.out.println("开始生成票据");
      new Properties();

      try {
         Properties props = PropertiesLoaderUtils.loadAllProperties("config.properties");
         String kerberos_command = props.getProperty("kerberos_command");
         String xmlpath = props.getProperty("hivexmlpath");
         System.out.println(kerberos_command);
         System.out.println(xmlpath);
         String value = TicketTool.getkrb5cc(kerberos_command);
         if (value == null) {
            return null;
         }

         TicketTool.updateHiveXml(xmlpath, value);
      } catch (Exception e) {
         e.printStackTrace();
         return null;
      }

      System.out.println("生成票据执行完成啦");
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      System.out.println("====================contextInitialized=======================");
      AddSchedulerParam asp = new AddSchedulerParam();
      asp.setCreateTime("");
      asp.setRulesDay("0");
      asp.setRulesHour("00,08,18");
      asp.setRulesMinute("00");
      asp.setRulesType("1");
      asp.setRuleValidity("0");
      asp.setSrName("rw");
      TCoreSchedulerRules rules = new TCoreSchedulerRules();
      Boolean isEdit = false;
      if (asp.getId() != "" && asp.getId() != null) {
         isEdit = true;
      }

      if (isEdit) {
         rules.setId(asp.getId());
      }

      rules.setId("2");
      rules.setSrname(asp.getSrName());
      rules.setRulestype(asp.getRulesType());
      rules.setRulesday(asp.getRulesDay());
      rules.setRuleshour(asp.getRulesHour());
      rules.setRulesminute(asp.getRulesMinute());
      rules.setExpression(QuartzUtil.getCronExpression(asp.getRulesType(), asp.getRulesDay(), asp.getRulesHour(), asp.getRulesMinute(), asp.getXloptions(), asp.getHowtime()));

      try {
         rules.setCreatetime(asp.getCreateTime().equals("") ? new Date() : sdf.parse(asp.getCreateTime()));
      } catch (ParseException e) {
         e.printStackTrace();
      }

      rules.setUpdatetime(new Date());
      rules.setRulevalidity(asp.getRuleValidity());
      TriggerKey triggerKey = new TriggerKey(rules.getId());
      JobKey jobKey = new JobKey(rules.getId() + "job");
      JobDataMap jobDataMap = new JobDataMap();
      jobDataMap.put("rulesType", rules.getRulestype());
      jobDataMap.put("schedulerId", rules.getId());

      try {
         QuartzUtil.addJob(GenerateTicketTaskJob.class, rules.getExpression(), jobKey, triggerKey, jobDataMap);
      } catch (SchedulerException e) {
         e.printStackTrace();
      } catch (ParseException e) {
         e.printStackTrace();
      }

      return "ok";
   }

   public ResultVO startSchedulerTask(String rulesid) {
      ResultVO rv = new ResultVO();
      List<String> idList = this.tCoreSchedulerRelationDao.querySchedulerRelationByRuleid(rulesid);
      TCoreSchedulerRules rules = (TCoreSchedulerRules)this.tCoreSchedulerRulesDao.queryUnique(new Criterion[]{Restrictions.eq("id", rulesid)});
      TriggerKey triggerKey = new TriggerKey(rulesid);
      JobKey jobKey = new JobKey(rulesid + "job");
      JobDataMap jobDataMap = new JobDataMap();
      jobDataMap.put("idList", idList);
      jobDataMap.put("rulesType", rules.getRulestype());
      jobDataMap.put("schedulerId", rulesid);

      try {
         QuartzUtil.addJob(MaskingTaskJob.class, rules.getExpression(), jobKey, triggerKey, jobDataMap);
         TCoreSchedulerRules tCoreSchedulerRules = (TCoreSchedulerRules)this.tCoreSchedulerRulesDao.get(rulesid);
         tCoreSchedulerRules.setRulevalidity("0");
         this.tCoreSchedulerRulesDao.update(tCoreSchedulerRules);
         rv.setMessage("success");
         rv.setResult(true);
         return rv;
      } catch (SchedulerException e) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         e.printStackTrace();
         rv.setMessage(e.getMessage());
         rv.setResult(false);
         return rv;
      } catch (ParseException e) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         e.printStackTrace();
         rv.setMessage(e.getMessage());
         rv.setResult(false);
         return rv;
      }
   }

   public ResultVO stopSchedulerTask(String rulesid) {
      ResultVO rv = new ResultVO();
      List<String> idList = this.tCoreSchedulerRelationDao.querySchedulerRelationByRuleid(rulesid);
      TCoreSchedulerRules rules = (TCoreSchedulerRules)this.tCoreSchedulerRulesDao.queryUnique(new Criterion[]{Restrictions.eq("id", rulesid)});
      TriggerKey triggerKey = new TriggerKey(rulesid);
      JobKey jobKey = new JobKey(rulesid + "job");
      JobDataMap jobDataMap = new JobDataMap();
      jobDataMap.put("idList", idList);
      jobDataMap.put("rulesType", rules.getRulestype());
      jobDataMap.put("schedulerId", rulesid);

      try {
         QuartzUtil.removeJob(jobKey);
         QuartzUtil.removeTrigger(triggerKey);
         TCoreSchedulerRules tCoreSchedulerRules = (TCoreSchedulerRules)this.tCoreSchedulerRulesDao.get(rulesid);
         tCoreSchedulerRules.setRulevalidity("1");
         if ("1".equals(tCoreSchedulerRules.getRulestype())) {
            tCoreSchedulerRules.setErrormessage("");
         }

         this.tCoreSchedulerRulesDao.update(tCoreSchedulerRules);
         rv.setResult(true);
      } catch (SchedulerException e) {
         e.printStackTrace();
         rv.setMessage(e.getMessage());
         rv.setResult(false);
      }

      return rv;
   }

   public List<Desensitizationtask> getAddUnSaveTask(String id) {
      return this.tCoreSchedulerRulesDao.getallTask(id);
   }

   public TCoreSchedulerRules selectscheduler(String id) {
      return (TCoreSchedulerRules)this.tCoreSchedulerRulesDao.queryUnique(new Criterion[]{Restrictions.eq("id", id)});
   }
}
