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.engine.ghca.webservice.DesensitizationEngineInterfaceImpl;
import com.chenyang.nse.bussiness.engine.ghca.webservice.DesensitizationEngineInterfaceImplService;
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.dataproject.TCoreDataProject;
import com.chenyang.nse.bussiness.entity.orm.table.core.desensitizationselftask.DesensitizationSelfTask;
import com.chenyang.nse.bussiness.entity.orm.table.core.desensitizationtask.DesensitizationMonitor;
import com.chenyang.nse.bussiness.entity.orm.table.core.desensitizationtask.DesensitizationMonitorInfo;
import com.chenyang.nse.bussiness.entity.orm.table.core.desensitizationtask.DesensitizationTablecolumn;
import com.chenyang.nse.bussiness.entity.orm.table.core.desensitizationtask.Desensitizationtask;
import com.chenyang.nse.bussiness.entity.orm.table.core.desensitizationtask.EncryptionMasking;
import com.chenyang.nse.bussiness.entity.vo.ComboboxVO;
import com.chenyang.nse.bussiness.entity.vo.DataGridVO;
import com.chenyang.nse.bussiness.entity.vo.DesensitizationMonitorVO;
import com.chenyang.nse.bussiness.service.core.DesensitizationMonitorService;
import com.chenyang.nse.bussiness.service.core.DesensitizationselftaskService;
import com.chenyang.nse.bussiness.service.core.DesensitizationtaskLogService;
import com.chenyang.nse.bussiness.service.core.DesensitizationtaskService;
import com.chenyang.nse.bussiness.service.core.EncryptionMaskingService;
import com.chenyang.nse.bussiness.service.core.ImportDesensitizationtaskService;
import com.chenyang.nse.bussiness.service.core.MaskingTaskService;
import com.chenyang.nse.bussiness.service.core.TdataProjectService;
import com.chenyang.nse.bussiness.tools.command.CommandTool;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
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;

@Controller
@RequestMapping({"/core/desensitizationmonitorlog"})
public class DesensitizationMonitorLogController {
   private static Logger logger = LoggerFactory.getLogger(DesensitizationMonitorLogController.class);
   @Autowired
   private MaskingTaskService maskingTaskService;
   @Autowired
   private DesensitizationtaskService desensitizationtaskService;
   @Autowired
   private DesensitizationtaskLogService desensitizationtaskLogService;
   @Autowired
   private ImportDesensitizationtaskService importDesensitizationtaskService;
   @Autowired
   private DesensitizationMonitorService desensitizationMonitorService;
   @Autowired
   private TdataProjectService tdataProjectService;
   @Autowired
   private EncryptionMaskingService encryptionmaskingService;
   @Autowired
   private DesensitizationselftaskService desensitizationSelfTaskService;

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

   @RequestMapping({"/selfmonitorpage"})
   public String selfmonitorpage(HttpServletRequest request, HttpServletResponse response, Model model) {
      return "core/desensitizationmonitorlog/newmonitorselftasklog";
   }

   @RequestMapping({"/projectmonitor"})
   public String projectmonitor(HttpServletRequest request, HttpServletResponse response, Model model) {
      String crud = request.getParameter("crud");
      String id = request.getParameter("id");
      String issch = request.getParameter("issch");
      model.addAttribute("id", id);
      model.addAttribute("crud", crud);
      model.addAttribute("issch", issch);
      return "core/desensitizationmonitorlog/projectmonitortasklog";
   }

   @RequestMapping({"/projectselfmonitor"})
   public String projectselfmonitor(HttpServletRequest request, HttpServletResponse response, Model model) {
      String crud = request.getParameter("crud");
      String id = request.getParameter("id");
      String issch = request.getParameter("issch");
      model.addAttribute("id", id);
      model.addAttribute("crud", crud);
      model.addAttribute("issch", issch);
      return "core/desensitizationmonitorlog/projectselfmonitortasklog";
   }

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

   @RequestMapping({"/queryProjectTaskAll"})
   @ResponseBody
   public List<Desensitizationtask> queryprojecttasklist(HttpServletRequest request, HttpServletResponse response, Model model, String projectid) {
      List<Desensitizationtask> list = this.desensitizationtaskService.queryTaskAllbyprojectid(projectid);
      return list;
   }

   @RequestMapping({"/queryProjectSelfTaskAll"})
   @ResponseBody
   public List<DesensitizationSelfTask> queryprojectselftasklist(HttpServletRequest request, HttpServletResponse response, Model model, String projectid) {
      List<DesensitizationSelfTask> list = this.desensitizationSelfTaskService.queryTaskAllbyprojectid(projectid);
      return list;
   }

   @RequestMapping({"/queryProjectAll"})
   @ResponseBody
   public List<ComboboxVO> queryProjectAll(HttpServletRequest request, HttpServletResponse response, Model model) {
      List<ComboboxVO> rtlist = new ArrayList();
      List<TCoreDataProject> list = this.tdataProjectService.selectDataProject();

      for(int i = 0; i < list.size(); ++i) {
         rtlist.add(new ComboboxVO(((TCoreDataProject)list.get(i)).getId(), ((TCoreDataProject)list.get(i)).getProject()));
      }

      return rtlist;
   }

   @ResponseBody
   @RequestMapping({"/queryTaskVersionList"})
   public List<ComboboxVO> queryTaskVersionList(HttpServletRequest request, HttpServletResponse response, Model model, String taskId) {
      List list = this.desensitizationMonitorService.queryTaskVersionList(taskId);
      List<ComboboxVO> listvo = 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).substring(0, 19);
         listvo.add(new ComboboxVO(list.get(i).toString(), res));
      }

      return listvo;
   }

   @ResponseBody
   @RequestMapping({"/querySelfTaskVersionList"})
   public List<ComboboxVO> querySelfTaskVersionList(HttpServletRequest request, HttpServletResponse response, Model model, String taskId) {
      List list = this.desensitizationMonitorService.querySelfTaskVersionList(taskId);
      List<ComboboxVO> listvo = 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).substring(0, 19);
         listvo.add(new ComboboxVO(list.get(i).toString(), res));
      }

      return listvo;
   }

   @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)) {
            String masking_engine_type = "";
            this.desensitizationtaskService.querySourceInfo(taskid);
            this.desensitizationtaskService.queryTargetById(taskid);
            this.desensitizationtaskService.queryTaskById(taskid);
            this.desensitizationtaskService.queryDesensitizationfileBytaskid(taskid);

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

            List<DesensitizationMonitor> list = null;
            if ("1".equals(masking_engine_type)) {
               list = this.desensitizationMonitorService.queryTaskLogMonitor(taskid, groupid, pageInfo, indexrow);
            } else {
               list = this.desensitizationMonitorService.queryTaskMonitor(taskid, groupid, pageInfo, indexrow);
            }

            Desensitizationtask task = this.desensitizationtaskService.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");
               String structureid = "";
               int fieldcount = 0;
               int maskingfieldcount = 0;
               String tablename = desensitizationMonitor.getSourcename();

               for(DesensitizationTablecolumn column : this.desensitizationtaskService.queryColumInfo(taskid, tablename)) {
                  if (!"".equals(column.getColumnname()) && column.getColumnname() != null) {
                     ++fieldcount;
                  }

                  if (!"".equals(column.getRulename()) && column.getRulename() != null) {
                     ++maskingfieldcount;
                  }
               }

               desensitizationMonitorVO.setFieldcount(fieldcount);
               desensitizationMonitorVO.setMaskingfieldcount(maskingfieldcount);
               listVo.add(desensitizationMonitorVO);
            }

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

   @RequestMapping({"/exeTaskMonitor"})
   @ResponseBody
   public SessionBean exeTaskMonitor(HttpServletRequest request, HttpServletResponse response, Model model, String taskid, String wfname, String monitorId, Long groupid, String logType) {
      DesensitizationEngineInterfaceImplService engineInterfaceImplService = new DesensitizationEngineInterfaceImplService();
      DesensitizationEngineInterfaceImpl engineInterfaceImpl = (DesensitizationEngineInterfaceImpl)engineInterfaceImplService.getPort(DesensitizationEngineInterfaceImpl.class);
      Desensitizationtask task = this.desensitizationtaskService.queryTaskById(taskid);
      SessionBean sessionbean = new SessionBean();
      List<SessionBeanDetail> sessionBeanDetailList = new ArrayList();
      int sucCnt = 0;

      try {
         new ArrayList();
         List e = engineInterfaceImpl.readFileToPage(task.getTasknamereal(), wfname, logType, groupid);
         if (e.size() > 0 && e != null) {
            for(int i = 0; i < e.size(); ++i) {
               String[] str = e.get(i).toString().split("#\\|\\|#");
               SessionBeanDetail sessionBeanDetail = new SessionBeanDetail();
               sessionBeanDetail.setWidgetInstanceName(str[0]);
               sessionBeanDetail.setTablename(str[0]);
               if (str[1].equals("1")) {
                  ++sucCnt;
               } else if (str[1].equals("0")) {
                  sessionbean.setStatus("RUNNING");
               } else {
                  sessionbean.setStatus("FAIL");
               }

               sessionbean.setStart_time(str[2]);
               sessionbean.setEnd_time(str[3]);
               sessionBeanDetail.setApplied_rows(Long.parseLong(str[4]));
               sessionBeanDetail.setAffected_rows(Long.parseLong(str[5]));
               sessionBeanDetail.setRejected_rows(Long.parseLong(str[6]));
               DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
               Long startdate = dateFormat.parse(str[2]).getTime();
               long throughput = 0L;
               if (str[1].equals("0")) {
                  throughput = Long.parseLong(str[5]) / (((new Date()).getTime() - startdate) / 1000L);
                  sessionBeanDetail.setThroughput(String.valueOf(throughput));
               } else {
                  sessionBeanDetail.setThroughput(str[7]);
               }

               sessionBeanDetail.setTabletype(str[8]);
               sessionBeanDetailList.add(sessionBeanDetail);
            }

            if (2 == sucCnt) {
               sessionbean.setStatus("SUCCEEDED");
            }
         }

         sessionbean.setSessionBeanDetail(sessionBeanDetailList);
      } catch (Exception e) {
         e.printStackTrace();
         SessionBean se = new SessionBean();
         se.setStatus("FAIL");
         return se;
      }

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

   @RequestMapping({"/exeTaskMonitorEM"})
   @ResponseBody
   public SessionBean exeTaskMonitorEM(HttpServletRequest request, HttpServletResponse response, Model model, String taskid, String wfname, String monitorId, Long groupid, String logType) {
      DesensitizationEngineInterfaceImplService engineInterfaceImplService = new DesensitizationEngineInterfaceImplService();
      DesensitizationEngineInterfaceImpl engineInterfaceImpl = (DesensitizationEngineInterfaceImpl)engineInterfaceImplService.getPort(DesensitizationEngineInterfaceImpl.class);
      EncryptionMasking task = this.encryptionmaskingService.queryTaskById(taskid);
      SessionBean sessionbean = new SessionBean();
      List<SessionBeanDetail> sessionBeanDetailList = new ArrayList();
      int sucCnt = 0;

      try {
         new ArrayList();
         List e = engineInterfaceImpl.readFileToPage(task.getTasknamereal(), wfname, logType, groupid);
         if (e.size() > 0 && e != null) {
            for(int i = 0; i < e.size(); ++i) {
               String[] str = e.get(i).toString().split("#\\|\\|#");
               SessionBeanDetail sessionBeanDetail = new SessionBeanDetail();
               sessionBeanDetail.setWidgetInstanceName(str[0]);
               sessionBeanDetail.setTablename(str[0]);
               if (str[1].equals("1")) {
                  ++sucCnt;
               } else if (str[1].equals("0")) {
                  sessionbean.setStatus("RUNNING");
               } else {
                  sessionbean.setStatus("FAIL");
               }

               sessionbean.setStart_time(str[2]);
               sessionbean.setEnd_time(str[3]);
               sessionBeanDetail.setApplied_rows(Long.parseLong(str[4]));
               sessionBeanDetail.setAffected_rows(Long.parseLong(str[5]));
               sessionBeanDetail.setRejected_rows(Long.parseLong(str[6]));
               DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
               Long startdate = dateFormat.parse(str[2]).getTime();
               long throughput = 0L;
               if (str[1].equals("0")) {
                  throughput = Long.parseLong(str[5]) / (((new Date()).getTime() - startdate) / 1000L);
                  sessionBeanDetail.setThroughput(String.valueOf(throughput));
               } else {
                  sessionBeanDetail.setThroughput(str[7]);
               }

               sessionBeanDetail.setTabletype(str[8]);
               sessionBeanDetailList.add(sessionBeanDetail);
            }

            if (2 == sucCnt) {
               sessionbean.setStatus("SUCCEEDED");
            }
         }

         sessionbean.setSessionBeanDetail(sessionBeanDetailList);
      } catch (Exception e) {
         e.printStackTrace();
         SessionBean se = new SessionBean();
         se.setStatus("FAIL");
         return se;
      }

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

   @RequestMapping({"/querySessionLog"})
   @ResponseBody
   public SessionBean querySessionLog(String taskid, String wfname, String monitorId, Long groupid, String logType, String isLoadMore) {
      DesensitizationEngineInterfaceImplService engineInterfaceImplService = new DesensitizationEngineInterfaceImplService();
      DesensitizationEngineInterfaceImpl engineInterfaceImpl = (DesensitizationEngineInterfaceImpl)engineInterfaceImplService.getPort(DesensitizationEngineInterfaceImpl.class);
      Desensitizationtask task = this.desensitizationtaskService.queryTaskById(taskid);
      SessionBean sessionbean = new SessionBean();
      List list = engineInterfaceImpl.readFileToPage(task.getTasknamereal(), wfname, logType, groupid);
      StringBuffer logLine = new StringBuffer();

      for(int i = 0; i < list.size(); ++i) {
         logLine.append(list.get(i)).append(System.getProperty("line.separator"));
         if ("0".equals(isLoadMore) && i == 5000) {
            logLine.append("<p style=\"text-align:center\"><a class=\"run-log\" href=\"javascript:;\" onclick=\"logDetails(1)\"  class=\"easyui-linkbutton\" data-options=\"plain:true,iconCls:\\'icon-zx\\'\">加载更多</a></p><br/>");
            break;
         }

         if ("1".equals(isLoadMore) && i == 10000) {
            break;
         }
      }

      sessionbean.setSe_log(logLine.toString());
      System.out.println("日志行数=" + list.size());
      return sessionbean;
   }

   @RequestMapping({"/querySessionLogEM"})
   @ResponseBody
   public SessionBean querySessionLogEM(String taskid, String wfname, String monitorId, Long groupid, String logType, String isLoadMore) {
      DesensitizationEngineInterfaceImplService engineInterfaceImplService = new DesensitizationEngineInterfaceImplService();
      DesensitizationEngineInterfaceImpl engineInterfaceImpl = (DesensitizationEngineInterfaceImpl)engineInterfaceImplService.getPort(DesensitizationEngineInterfaceImpl.class);
      EncryptionMasking task = this.encryptionmaskingService.queryTaskById(taskid);
      SessionBean sessionbean = new SessionBean();
      List list = engineInterfaceImpl.readFileToPage(task.getTasknamereal(), wfname, logType, groupid);
      StringBuffer logLine = new StringBuffer();

      for(int i = 0; i < list.size(); ++i) {
         logLine.append(list.get(i)).append(System.getProperty("line.separator"));
         if ("0".equals(isLoadMore) && i == 5000) {
            logLine.append("<p style=\"text-align:center\"><a class=\"run-log\" href=\"javascript:;\" onclick=\"logDetails(1)\"  class=\"easyui-linkbutton\" data-options=\"plain:true,iconCls:\\'icon-zx\\'\">加载更多</a></p><br/>");
            break;
         }

         if ("1".equals(isLoadMore) && i == 10000) {
            break;
         }
      }

      sessionbean.setSe_log(logLine.toString());
      System.out.println("日志行数=" + list.size());
      return sessionbean;
   }

   @RequestMapping({"/queryImportData"})
   @ResponseBody
   public String queryImportData(HttpServletRequest request, HttpServletResponse response, Model model, String[] taskidlist) {
      DesensitizationEngineInterfaceImplService engineInterfaceImplService = new DesensitizationEngineInterfaceImplService();
      DesensitizationEngineInterfaceImpl engineInterfaceImpl = (DesensitizationEngineInterfaceImpl)engineInterfaceImplService.getPort(DesensitizationEngineInterfaceImpl.class);
      new ArrayList();

      for(DesensitizationMonitor monitorInfo : this.desensitizationtaskLogService.queryImportData()) {
         List list = engineInterfaceImpl.readFileToPage(monitorInfo.getTasknamereal(), monitorInfo.getSourcename(), "P", monitorInfo.getGroupid().longValue());
         if (list.size() > 0 && list != null) {
            for(int i = 0; i < list.size(); ++i) {
               try {
                  DesensitizationMonitorInfo desensitizationMonitorInfo = new DesensitizationMonitorInfo();
                  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                  String[] str = list.get(i).toString().split("#\\|\\|#");
                  desensitizationMonitorInfo.setInstancename(str[0]);
                  desensitizationMonitorInfo.setMonitorid(monitorInfo.getId());
                  desensitizationMonitorInfo.setTaskid(monitorInfo.getTaskid());
                  desensitizationMonitorInfo.setStarttime(sdf.parse(str[2]));
                  desensitizationMonitorInfo.setEndtime(sdf.parse(str[3]));
                  desensitizationMonitorInfo.setCreatetime(new Date());
                  if (str[1].equals("1")) {
                     desensitizationMonitorInfo.setRunstatus("SUCCEEDED");
                  } else if (str[1].equals("0")) {
                     desensitizationMonitorInfo.setRunstatus("RUNNING");
                  } else {
                     desensitizationMonitorInfo.setRunstatus("FAIL");
                  }

                  desensitizationMonitorInfo.setNumappliedrows(str[4] + "");
                  desensitizationMonitorInfo.setNumaffectedrows(str[5] + "");
                  desensitizationMonitorInfo.setNumrejectedrows(str[6] + "");
                  desensitizationMonitorInfo.setThroughput("0");
                  desensitizationMonitorInfo.setWidgettype(str[8]);
                  this.desensitizationtaskLogService.saveMonitorInfo(desensitizationMonitorInfo);
               } catch (ParseException e) {
                  e.printStackTrace();
               }
            }
         }

         monitorInfo.setIsimport("1");
         this.desensitizationMonitorService.update(monitorInfo);
      }

      return "SUCESS";
   }

   @RequestMapping({"/stoptasktb"})
   @ResponseBody
   public String stopTaskTable(HttpServletRequest request, HttpServletResponse response, Model model, String taskid, String wfname, String monitorId, Long groupid) {
      Desensitizationtask task = this.desensitizationtaskService.queryTaskById(taskid);

      try {
         String command = "ps -ef|grep \"masking-engine.jar " + task.getTasknamereal() + " " + wfname + " " + groupid + " \"|grep -v grep|awk  '{print \"kill -9 \" $2}' |sh";
         CommandTool.commandPipeRtn(command);
         this.desensitizationtaskService.updateEngineStopFlag(taskid, wfname, groupid.toString(), "3");
      } catch (Exception e) {
         e.printStackTrace();
      }

      return "任务停止成功";
   }
}
