package com.chenyang.nse.bussiness.controller.core;

import com.chenyang.nse.bussiness.config.PropertiesLoaderUtils;
import com.chenyang.nse.bussiness.dao.PageInfo;
import com.chenyang.nse.bussiness.dao.core.EngineDao;
import com.chenyang.nse.bussiness.dao.table.core.TCoreEngineDao;
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.entity.orm.table.core.ImportMaskingExecute;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreEngine;
import com.chenyang.nse.bussiness.entity.orm.table.core.desensitizationtask.DesensitizationMonitor;
import com.chenyang.nse.bussiness.entity.orm.table.core.desensitizationtask.Desensitizationtask;
import com.chenyang.nse.bussiness.entity.vo.DataGridVO;
import com.chenyang.nse.bussiness.entity.vo.DesensitizationMonitorVO;
import com.chenyang.nse.bussiness.entity.vo.ProgressVO;
import com.chenyang.nse.bussiness.entity.vo.ResultVO;
import com.chenyang.nse.bussiness.service.core.DesensitizationtaskService;
import com.chenyang.nse.bussiness.service.core.DmpDesensitizationMonitorService;
import com.chenyang.nse.bussiness.service.core.DmpDesensitizationService;
import com.chenyang.nse.bussiness.service.core.ImportDesensitizationtaskService;
import com.chenyang.nse.bussiness.service.core.MaskingTaskService;
import com.chenyang.nse.bussiness.tools.object.ObjectTool;
import com.chenyang.nse.bussiness.tools.redis.RedisClient;
import java.io.IOException;
import java.text.DecimalFormat;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

@Controller
@RequestMapping({"/core/dmpdesensitizationmonitor"})
public class DmpDesensitizationMonitorController {
   private static Logger logger = LoggerFactory.getLogger(DmpDesensitizationMonitorController.class);
   @Autowired
   private MaskingTaskService maskingTaskService;
   @Autowired
   private DmpDesensitizationService dmpDesensitizationService;
   @Autowired
   private DesensitizationtaskService desensitizationService;
   @Autowired
   private ImportDesensitizationtaskService importDesensitizationtaskService;
   @Autowired
   private TCoreEngineDao tCoreEngineDao;
   @Autowired
   private EngineDao engineDao;
   @Autowired
   private DmpDesensitizationMonitorService dmpDesensitizationMonitorService;

   @RequestMapping
   public String index(HttpServletRequest request, HttpServletResponse response, Model model) {
      return "core/desensitizationmonitordmp/monitortask";
   }

   @ResponseBody
   @RequestMapping({"/querytasklist"})
   public List<Desensitizationtask> querytasklist(HttpServletRequest request, HttpServletResponse response, Model model) {
      List<Desensitizationtask> list = this.dmpDesensitizationService.queryTaskAll();
      return list;
   }

   @ResponseBody
   @RequestMapping({"/querytasklistByPage"})
   public DataGridVO<Desensitizationtask> querytasklistByPage(Integer page, Integer rows, PageInfo pageInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
      pageInfo.setPageno(page);
      pageInfo.setPagesize(rows);
      List<Desensitizationtask> list = this.dmpDesensitizationService.queryTaskByPage(pageInfo);
      DataGridVO<Desensitizationtask> vo = new DataGridVO<Desensitizationtask>(pageInfo.getCount(), list);
      return vo;
   }

   @ResponseBody
   @RequestMapping({"/querytmporary"})
   public DataGridVO<DesensitizationMonitorVO> querytmporary(String taskid, String groupid, Integer indexrow, Integer page, Integer rows, PageInfo pageInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
      pageInfo.setPageno(page);
      pageInfo.setPagesize(rows);
      if (taskid != null && !"".equals(taskid)) {
         if (groupid != null && !"".equals(groupid)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            long ts = 0L;

            try {
               Date date = sdf.parse(groupid);
               ts = date.getTime();
            } catch (ParseException e) {
               e.printStackTrace();
            }

            String res = String.valueOf(ts);
            List<DesensitizationMonitor> list = this.dmpDesensitizationMonitorService.queryTaskMonitor(taskid, res, pageInfo, indexrow);
            Desensitizationtask task = this.dmpDesensitizationService.queryTaskById(taskid);
            List<DesensitizationMonitorVO> listVo = new ArrayList();

            for(DesensitizationMonitor desensitizationMonitor : list) {
               DesensitizationMonitorVO desensitizationMonitorVO = new DesensitizationMonitorVO();
               desensitizationMonitorVO.setSourcename(desensitizationMonitor.getSourcename());
               desensitizationMonitorVO.setTargetname(desensitizationMonitor.getTargetname());
               desensitizationMonitorVO.setTasktype(desensitizationMonitor.getTasktype());
               desensitizationMonitorVO.setExecutetime(desensitizationMonitor.getExecutetime());
               desensitizationMonitorVO.setFlag(desensitizationMonitor.getFlag());
               desensitizationMonitorVO.setRunstatus(desensitizationMonitor.getRunstatus());
               desensitizationMonitorVO.setId(desensitizationMonitor.getId());
               desensitizationMonitorVO.setTaskid(desensitizationMonitor.getTaskid());
               desensitizationMonitorVO.setGroupid(desensitizationMonitor.getGroupid());
               desensitizationMonitorVO.setNote(desensitizationMonitor.getNote());
               desensitizationMonitorVO.setRunid(desensitizationMonitor.getRunid());
               desensitizationMonitorVO.setIsRecoverState("1".equals(task.getIsrecover()) ? "1" : "0");
               listVo.add(desensitizationMonitorVO);
            }

            DataGridVO<DesensitizationMonitorVO> vo = new DataGridVO<DesensitizationMonitorVO>(pageInfo.getCount(), listVo);
            return vo;
         } else {
            return null;
         }
      } else {
         return null;
      }
   }

   @ResponseBody
   @RequestMapping({"/queryTaskVersionList"})
   public List<Map<String, String>> queryTaskVersionList(HttpServletRequest request, HttpServletResponse response, Model model, String taskId) {
      List list = this.dmpDesensitizationMonitorService.queryTaskVersionList(taskId);
      List<Map<String, String>> listMap = new ArrayList();

      for(int i = 0; i < list.size(); ++i) {
         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
         long lt = new Long(list.get(i).toString());
         Date date = new Date(lt);
         String res = simpleDateFormat.format(date);
         Map<String, String> map = new HashMap();
         map.put("groupid", res);
         listMap.add(map);
      }

      return listMap;
   }

   @ResponseBody
   @RequestMapping({"/querytaskobj"})
   public List<Desensitizationtask> querytaskobj(String taskid, HttpServletRequest request, HttpServletResponse response, Model model) {
      List<Desensitizationtask> task = this.dmpDesensitizationService.queryTaskList(taskid);
      return task;
   }

   @ResponseBody
   @RequestMapping({"/queryimporttaskobj"})
   public List<ImportMaskingExecute> queryimporttaskobj(String taskid, HttpServletRequest request, HttpServletResponse response, Model model) {
      List<ImportMaskingExecute> task = this.importDesensitizationtaskService.queryTaskList(taskid);
      return task;
   }

   @RequestMapping({"/exeTaskMonitor"})
   @ResponseBody
   public SessionBean exeTaskMonitor(HttpServletRequest request, HttpServletResponse response, Model model, String taskid, String wfname, String monitorId) {
      Desensitizationtask task = this.dmpDesensitizationService.queryTaskById(taskid);
      new Properties();
      new SessionBean();
      RedisClient redisClient = new RedisClient();
      Jedis jedis = redisClient.getJedis();

      SessionBean sessionbean;
      try {
         Properties props = PropertiesLoaderUtils.loadAllProperties("config.properties");
         String engineid = props.getProperty("engineid");
         TCoreEngine tengine = (TCoreEngine)this.tCoreEngineDao.get(engineid);
         Map<String, Object> enginemap = this.engineDao.queryEnginePropertyKeyValue(tengine.getId());
         InfoProperty info = (InfoProperty)ObjectTool.getObjectByMap(InfoProperty.class, enginemap);
         sessionbean = this.dmpDesensitizationMonitorService.getLogForTaskMapping(task.getFoldername(), info, task.getTasknamereal() + "_" + wfname, jedis);
      } catch (Exception var16) {
         SessionBean se = new SessionBean();
         se.setStatus("FAIL");
         jedis.close();
         return se;
      }

      jedis.close();
      model.addAttribute("taskid", taskid);
      model.addAttribute("wfname", wfname);
      model.addAttribute("tmpid", monitorId);
      return sessionbean;
   }

   @RequestMapping({"/monitorCount"})
   @ResponseBody
   public void monitorCount(HttpServletRequest request, HttpServletResponse response, Model model, String progressid) {
      String absolutely = "60%";
      new Properties();
      new SessionBean();
      Map map = (Map)request.getSession().getAttribute("instantfilemasking");
      String stamp = (String)map.get("stamp");
      String folder = (String)map.get("folder");
      Long longcount = (Long)map.get("longcount");
      ProgressVO progressVO = new ProgressVO();

      try {
         Properties props = PropertiesLoaderUtils.loadAllProperties("config.properties");
         String engineid = props.getProperty("engineid");
         TCoreEngine tengine = (TCoreEngine)this.tCoreEngineDao.get(engineid);
         Map<String, Object> enginemap = this.engineDao.queryEnginePropertyKeyValue(tengine.getId());
         InfoProperty info = (InfoProperty)ObjectTool.getObjectByMap(InfoProperty.class, enginemap);
         SessionBean sessionbean = this.dmpDesensitizationMonitorService.getLogForMappingByInstantFile(folder, info, "s" + stamp, longcount);
         Long applied_rows = ((SessionBeanDetail)sessionbean.getSessionBeanDetail().get(0)).getApplied_rows();
         Long rejected_rows = ((SessionBeanDetail)sessionbean.getSessionBeanDetail().get(0)).getRejected_rows();
         Long run_rows = applied_rows + rejected_rows;
         if (longcount == 0L) {
            longcount = new Long(1L);
         }

         DecimalFormat df = new DecimalFormat("######0.00");
         absolutely = df.format((double)60.0F + (double)run_rows / (double)longcount * 0.4 * (double)100.0F);
         if ("FAILED".equals(sessionbean.getStatus())) {
            progressVO.setProgressid(progressid);
            progressVO.setProgresscontent("执行脱敏敏任务失败");
            progressVO.setProgressState(false);
            progressVO.setProgressValue(new Double((double)99.0F));
         } else {
            progressVO.setProgressid(progressid);
            progressVO.setProgresscontent("正在执行脱敏任务......");
            progressVO.setProgressState(true);
            progressVO.setProgressValue(new Double(absolutely));
         }

         request.getSession().setAttribute("progress", progressVO);
      } catch (Exception e) {
         System.out.println(e);
      }

   }

   @RequestMapping({"/exeImportTaskMonitor"})
   @ResponseBody
   public SessionBean exeImportTaskMonitor(HttpServletRequest request, HttpServletResponse response, Model model, String taskid, String wfname, String monitorId) {
      ImportMaskingExecute task = this.importDesensitizationtaskService.getImportMaskingExecute(taskid);
      new Properties();
      new SessionBean();
      RedisClient redisClient = new RedisClient();
      Jedis jedis = redisClient.getJedis();

      SessionBean sessionbean;
      try {
         Properties props = PropertiesLoaderUtils.loadAllProperties("config.properties");
         String engineid = props.getProperty("engineid");
         TCoreEngine tengine = (TCoreEngine)this.tCoreEngineDao.get(engineid);
         Map<String, Object> enginemap = this.engineDao.queryEnginePropertyKeyValue(tengine.getId());
         InfoProperty info = (InfoProperty)ObjectTool.getObjectByMap(InfoProperty.class, enginemap);
         sessionbean = this.dmpDesensitizationMonitorService.getLogForTaskMapping(task.getFoldername(), info, task.getTaskname().replace("wf_", ""), jedis);
      } catch (Exception var16) {
         SessionBean se = new SessionBean();
         se.setStatus("FAIL");
         jedis.close();
         return se;
      }

      jedis.close();
      model.addAttribute("taskid", taskid);
      model.addAttribute("wfname", wfname);
      model.addAttribute("tmpid", monitorId);
      return sessionbean;
   }

   @ResponseBody
   @RequestMapping({"/queryInportTmporary"})
   public DataGridVO<DesensitizationMonitor> queryInportTmporary(String taskid, String groupid, Integer indexrow, Integer page, Integer rows, PageInfo pageInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
      pageInfo.setPageno(page);
      pageInfo.setPagesize(rows);
      if (taskid != null && !"".equals(taskid)) {
         if (groupid != null && !"".equals(groupid)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            long ts = 0L;

            try {
               Date date = sdf.parse(groupid);
               ts = date.getTime();
            } catch (ParseException e) {
               e.printStackTrace();
            }

            String res = String.valueOf(ts);
            List<DesensitizationMonitor> list = this.dmpDesensitizationMonitorService.queryImportTaskMonitor(taskid, res, pageInfo, indexrow);
            DataGridVO<DesensitizationMonitor> vo = new DataGridVO<DesensitizationMonitor>(pageInfo.getCount(), list);
            return vo;
         } else {
            return null;
         }
      } else {
         return null;
      }
   }

   @RequestMapping({"/updateMonitorTaskState"})
   @ResponseBody
   public void updateMonitorTaskState(String monitorId, String state, HttpServletRequest request, HttpServletResponse response, Model model) {
      DesensitizationMonitor desensitizationMonitor = this.dmpDesensitizationMonitorService.getMonitorById(monitorId);
      if ("1".equals(state) || "2".equals(state)) {
         desensitizationMonitor.setFlag(state);
         this.dmpDesensitizationMonitorService.update(desensitizationMonitor);
      }
   }

   @RequestMapping({"/stopworkflow"})
   @ResponseBody
   public ResultVO stopWorkflow(String taskid, String wfname, HttpServletRequest request, HttpServletResponse response, Model model) {
      Desensitizationtask task = this.dmpDesensitizationService.queryTaskById(taskid);
      new Properties();
      String stopWorkflow = "FAIL";

      try {
         String schemaName = wfname.substring(0, wfname.lastIndexOf("-"));
         String tableName = wfname.substring(wfname.lastIndexOf("-") + 1, wfname.length());
         wfname = schemaName + "_" + tableName;
         Properties props = PropertiesLoaderUtils.loadAllProperties("config.properties");
         String engineid = props.getProperty("engineid");
         TCoreEngine tengine = (TCoreEngine)this.tCoreEngineDao.get(engineid);
         Map<String, Object> enginemap = this.engineDao.queryEnginePropertyKeyValue(tengine.getId());
         InfoProperty info = (InfoProperty)ObjectTool.getObjectByMap(InfoProperty.class, enginemap);
         stopWorkflow = this.dmpDesensitizationMonitorService.stopWorkflow(info, task.getTasknamereal() + "_" + wfname, task.getFoldername());
      } catch (IOException e) {
         e.printStackTrace();
      }

      return !"FAIL".equals(stopWorkflow) ? new ResultVO("执行成功", true) : new ResultVO("执行失败", false);
   }

   @RequestMapping({"/recoverworkflow"})
   @ResponseBody
   public ResultVO recoverworkflow(String taskid, String wfname, HttpServletRequest request, HttpServletResponse response, Model model) {
      Desensitizationtask task = this.dmpDesensitizationService.queryTaskById(taskid);
      new Properties();
      String recoverWorkflow = "FAIL";

      try {
         String schemaName = wfname.substring(0, wfname.lastIndexOf("-"));
         String tableName = wfname.substring(wfname.lastIndexOf("-") + 1, wfname.length());
         wfname = schemaName + "_" + tableName;
         Properties props = PropertiesLoaderUtils.loadAllProperties("config.properties");
         String engineid = props.getProperty("engineid");
         TCoreEngine tengine = (TCoreEngine)this.tCoreEngineDao.get(engineid);
         Map<String, Object> enginemap = this.engineDao.queryEnginePropertyKeyValue(tengine.getId());
         InfoProperty info = (InfoProperty)ObjectTool.getObjectByMap(InfoProperty.class, enginemap);
         recoverWorkflow = this.dmpDesensitizationMonitorService.recoverWorkflow(info, task.getTasknamereal() + "_" + wfname, task.getFoldername());
      } catch (IOException e) {
         e.printStackTrace();
      }

      return !"FAIL".equals(recoverWorkflow) ? new ResultVO("执行成功", true) : new ResultVO("执行失败", false);
   }

   @RequestMapping({"/querySessionLog"})
   @ResponseBody
   public SessionBean querySessionLog(String taskid, String wfname) {
      new Properties();
      SessionBean sessionbean = new SessionBean();

      try {
         String schemaName = wfname.substring(0, wfname.lastIndexOf("-"));
         String tableName = wfname.substring(wfname.lastIndexOf("-") + 1, wfname.length());
         wfname = schemaName + "_" + tableName;
         Desensitizationtask task = this.dmpDesensitizationService.queryTaskById(taskid);
         Properties props = PropertiesLoaderUtils.loadAllProperties("config.properties");
         String engineid = props.getProperty("engineid");
         TCoreEngine tengine = (TCoreEngine)this.tCoreEngineDao.get(engineid);
         Map<String, Object> enginemap = this.engineDao.queryEnginePropertyKeyValue(tengine.getId());
         InfoProperty engine = (InfoProperty)ObjectTool.getObjectByMap(InfoProperty.class, enginemap);
         sessionbean = this.dmpDesensitizationMonitorService.getSessionLog(task.getFoldername(), task.getTasknamereal() + "_" + wfname, engine);
      } catch (IOException e) {
         e.printStackTrace();
      }

      return sessionbean;
   }

   @RequestMapping({"/queryImportSessionLog"})
   @ResponseBody
   public SessionBean queryImportSessionLog(String taskid, String wfname) {
      new Properties();
      SessionBean sessionbean = new SessionBean();

      try {
         ImportMaskingExecute task = this.importDesensitizationtaskService.getImportMaskingExecute(taskid);
         Properties props = PropertiesLoaderUtils.loadAllProperties("config.properties");
         String engineid = props.getProperty("engineid");
         TCoreEngine tengine = (TCoreEngine)this.tCoreEngineDao.get(engineid);
         Map<String, Object> enginemap = this.engineDao.queryEnginePropertyKeyValue(tengine.getId());
         InfoProperty engine = (InfoProperty)ObjectTool.getObjectByMap(InfoProperty.class, enginemap);
         sessionbean = this.dmpDesensitizationMonitorService.getSessionLog(task.getFoldername(), task.getTaskname().replace("wf_", ""), engine);
      } catch (IOException e) {
         e.printStackTrace();
      }

      return sessionbean;
   }
}
