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

import com.chenyang.nse.bussiness.dao.PageInfo;
import com.chenyang.nse.bussiness.entity.cache.LoginUser;
import com.chenyang.nse.bussiness.entity.orm.table.console.TConsoleLog;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystem;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreEngine;
import com.chenyang.nse.bussiness.entity.orm.table.core.file.TCoreFileStructure;
import com.chenyang.nse.bussiness.entity.orm.table.core.masking.TCoreMaskingDetailrecord;
import com.chenyang.nse.bussiness.entity.orm.table.core.masking.TCoreMaskingRule;
import com.chenyang.nse.bussiness.entity.orm.table.core.maskingself.TCoreMaskingselfTable;
import com.chenyang.nse.bussiness.entity.orm.table.core.maskingself.TCoreMaskingselfTask;
import com.chenyang.nse.bussiness.entity.param.maskingself.SaveSelfParam;
import com.chenyang.nse.bussiness.entity.vo.ComboboxVO;
import com.chenyang.nse.bussiness.entity.vo.DBTableVO;
import com.chenyang.nse.bussiness.entity.vo.DataGridVO;
import com.chenyang.nse.bussiness.entity.vo.ResultVO;
import com.chenyang.nse.bussiness.entity.vo.maskingself.ModifyInfo;
import com.chenyang.nse.bussiness.entity.vo.maskingself.SourceInfo;
import com.chenyang.nse.bussiness.entity.vo.maskingself.TaskInfo;
import com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO;
import com.chenyang.nse.bussiness.entity.vo.maskingtask.TaskRecordVO;
import com.chenyang.nse.bussiness.enumeration.EmaskingTaskType;
import com.chenyang.nse.bussiness.service.console.OperationService;
import com.chenyang.nse.bussiness.service.core.DataSystemService;
import com.chenyang.nse.bussiness.service.core.FileSystemService;
import com.chenyang.nse.bussiness.service.core.ImportMaskingRuleService;
import com.chenyang.nse.bussiness.service.core.MaskingRuleService;
import com.chenyang.nse.bussiness.service.core.MaskingSelfTaskService;
import com.chenyang.nse.bussiness.service.core.MaskingTaskService;
import com.chenyang.nse.bussiness.service.info.InfoSelfService;
import com.chenyang.nse.bussiness.service.info.InfoService;
import com.chenyang.nse.bussiness.tools.jdbc.JdbcTool;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({"/core/maskingselftask"})
public class MaskingSelfTaskController {
   private static Logger logger = LoggerFactory.getLogger(MaskingSelfTaskController.class);
   @Autowired
   private ImportMaskingRuleService importMaskingRuleService;
   @Autowired
   private InfoService infoService;
   @Autowired
   private DataSystemService dataSystemService;
   @Autowired
   private MaskingRuleService maskingRuleService;
   @Autowired
   private MaskingTaskService maskingTaskService;
   @Autowired
   private MaskingSelfTaskService maskingSelfTaskService;
   @Autowired
   private InfoSelfService infoSelfService;
   @Autowired
   private FileSystemService fileSystemService;
   @Autowired
   private OperationService operationService;

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

   @RequestMapping({"/createtask"})
   public String createtask(String taskid, HttpServletRequest request, HttpServletResponse response, Model model) {
      model.addAttribute("taskid", taskid);
      return "core/maskingselftask/createstep/createtask";
   }

   @RequestMapping({"/createtaskstep"})
   public String createtaskstep(String step, HttpServletRequest request, HttpServletResponse response, Model model) {
      return "core/maskingselftask/createstep/" + step;
   }

   @RequestMapping({"/datatype"})
   public String datatype(String type, String flag, HttpServletRequest request, HttpServletResponse response, Model model) {
      return "core/maskingselftask/createstep/" + type + "/" + flag;
   }

   @RequestMapping({"/querytasktype"})
   @ResponseBody
   public List<ComboboxVO> querytasktype(HttpServletRequest request, HttpServletResponse response, Model model) {
      List<ComboboxVO> list = new ArrayList();

      for(EmaskingTaskType e : EmaskingTaskType.values()) {
         ComboboxVO c = new ComboboxVO(e.getFlag(), e.getMaskingtype());
         list.add(c);
      }

      return list;
   }

   @ResponseBody
   @RequestMapping({"/querymaskingengine"})
   public List<TCoreEngine> querymaskingengine(HttpServletRequest request, HttpServletResponse response, Model model) {
      List<TCoreEngine> list = this.importMaskingRuleService.queryMaskingEngine();
      return list;
   }

   @ResponseBody
   @RequestMapping({"/queryfolder"})
   public List<Map<String, String>> queryfolder(String engineid, HttpServletRequest request, HttpServletResponse response, Model model) {
      List<String> folder = this.infoService.queryFolderList(engineid);
      List<Map<String, String>> list = new ArrayList();

      for(String item : folder) {
         Map<String, String> map = new HashMap();
         map.put("id", item);
         map.put("text", item);
         map.put("iconCls", "icon-folder");
         list.add(map);
      }

      return list;
   }

   @RequestMapping({"/querydatasystem"})
   @ResponseBody
   public List<TCoreDatasystem> querydatasystem(HttpServletRequest request, HttpServletResponse response, Model model) {
      String flag = "1";
      List<TCoreDatasystem> list = this.dataSystemService.query(flag);
      return list;
   }

   @RequestMapping({"/queryschema"})
   @ResponseBody
   public List<ComboboxVO> queryschema(String datasystemid, HttpServletRequest request, HttpServletResponse response, Model model) {
      Connection conn = this.dataSystemService.getConnectionByDataSystemId(datasystemid);
      List<String> schema = JdbcTool.getDbSchemas(conn);
      JdbcTool.closeConnection(conn);
      List<ComboboxVO> list = new ArrayList();

      for(String str : schema) {
         ComboboxVO cv = new ComboboxVO(str);
         list.add(cv);
      }

      return list;
   }

   @RequestMapping({"/inputmulti"})
   public String inputmulti(String flag, String title, String multivalue, HttpServletRequest request, HttpServletResponse response, Model model) {
      model.addAttribute("title", title);
      model.addAttribute("multivalue", multivalue);
      return "core/maskingselftask/createstep/step03/" + flag;
   }

   @RequestMapping({"/topreviewlayout"})
   public String topreviewlayout() {
      return "core/maskingselftask/createstep/step04/multi";
   }

   @RequestMapping({"/inittabledg"})
   @ResponseBody
   public DataGridVO<DBTableVO> inittabledg(String datasystemid, String schema) {
      List<DBTableVO> list = this.dataSystemService.queryTablename(datasystemid, schema);
      return new DataGridVO<DBTableVO>((long)list.size(), list);
   }

   @RequestMapping({"/querymaskingrule"})
   @ResponseBody
   public List<TCoreMaskingRule> querymaskingrule() {
      return this.maskingRuleService.queryMaskingRule();
   }

   @RequestMapping({"/querycolumninfo"})
   @ResponseBody
   public List<ColumnInfoVO> querycolumninfo(String id, String schema, String tablename, HttpServletRequest request, HttpServletResponse response, Model model) {
      String datasystemid = id.replace(tablename, "");
      TCoreDatasystem datasystem = this.dataSystemService.queryDataSystemById(datasystemid);
      if (datasystem == null) {
         return null;
      } else {
         Connection conn = this.maskingTaskService.getConnectionByDataSystemId(datasystemid);
         List<ColumnInfoVO> list = JdbcTool.getColumnInfoVO(conn, schema, tablename);

         try {
            if (conn != null) {
               conn.close();
            }
         } catch (SQLException e) {
            e.printStackTrace();
         }

         return list;
      }
   }

   @RequestMapping(
      value = {"/addtask"},
      method = {RequestMethod.POST}
   )
   @ResponseBody
   public ResultVO addtask(@RequestBody SaveSelfParam ssp, HttpServletRequest request) {
      LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
      ssp.setUserId(loginUser.getTsysUser().getId());
      ssp.setUsername(loginUser.getTsysUser().getUsername());
      ResultVO rv = this.maskingSelfTaskService.addAndModifyMaskingTask(ssp);
      return rv;
   }

   @RequestMapping({"/querytask"})
   @ResponseBody
   public DataGridVO<TCoreMaskingselfTask> querytask(String engineid, String taskname, Integer page, Integer rows, PageInfo pageInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
      if (engineid != null && !"".equals(engineid)) {
         pageInfo.setPageno(page);
         pageInfo.setPagesize(rows);
         List<TCoreMaskingselfTask> list = this.maskingSelfTaskService.queryTask(engineid, taskname, pageInfo);
         DataGridVO<TCoreMaskingselfTask> vo = new DataGridVO<TCoreMaskingselfTask>(pageInfo.getCount(), list);
         return vo;
      } else {
         return null;
      }
   }

   @RequestMapping({"/querytasklist"})
   @ResponseBody
   public List<TCoreMaskingselfTask> querytasklist(String engineid, String taskname, HttpServletRequest request, HttpServletResponse response, Model model) {
      if (engineid != null && !"".equals(engineid)) {
         List<TCoreMaskingselfTask> list = this.maskingSelfTaskService.querytasklist(engineid, taskname);
         return list;
      } else {
         return null;
      }
   }

   @RequestMapping({"/querytasklistlog"})
   @ResponseBody
   public List<TCoreMaskingselfTask> querytasklistlog(String engineid, String taskname, HttpServletRequest request, HttpServletResponse response, Model model) {
      List<TCoreMaskingselfTask> list = this.maskingSelfTaskService.querytasklist(engineid, taskname);
      return list;
   }

   @RequestMapping(
      value = {"/removetask"},
      method = {RequestMethod.POST}
   )
   @ResponseBody
   public void removetask(HttpServletRequest request, String taskid) {
      this.maskingSelfTaskService.removeTask(taskid);
      this.maskingTaskService.removeRecord(taskid);
      logger.info("删除脱敏任务");
      TConsoleLog record = new TConsoleLog();
      LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
      String username = loginUser.getTsysUser().getUsername();
      record.setModule("本库脱敏");
      record.setOperationtime(new Date());
      record.setUser(username);
      record.setLogmessage("删除本库脱敏任务");
      this.operationService.add(record);
   }

   @RequestMapping({"/detail"})
   public String detail(String tasktype, String taskid, HttpServletRequest request, HttpServletResponse response, Model model) {
      model.addAttribute("taskid", taskid);
      model.addAttribute("tasktype", tasktype);
      return "core/maskingselftask/maskingselftaskdetail";
   }

   @RequestMapping({"/querytaskdetail"})
   @ResponseBody
   public Map<String, Object> querytaskdetail(String taskid) {
      return this.maskingSelfTaskService.queryTaskDetail(taskid);
   }

   @RequestMapping({"/querytaskdetailinfo"})
   @ResponseBody
   public Map<String, Object> querytaskdetailinfo(String taskid, String datadirection) {
      return this.maskingSelfTaskService.queryTaskDetailInfo(taskid, datadirection);
   }

   @RequestMapping({"/querymultitable"})
   @ResponseBody
   public List<Map<String, Object>> querymultitable(String sourceid) {
      return this.maskingSelfTaskService.querymultitable(sourceid);
   }

   @RequestMapping({"/testtasknameexist"})
   @ResponseBody
   public ResultVO testtasknameexist(String engineid, String taskname, HttpServletRequest request, HttpServletResponse response, Model model) {
      TCoreMaskingselfTask tCoreMaskingselfTask = this.maskingSelfTaskService.queryEngineMaskingTaskByTaskName(engineid, taskname);
      return tCoreMaskingselfTask != null ? new ResultVO(tCoreMaskingselfTask.getTaskname(), true) : new ResultVO("", false);
   }

   @RequestMapping({"/querymaskingtask"})
   @ResponseBody
   public ModifyInfo querymaskingtask(String taskid) {
      ModifyInfo mi = new ModifyInfo();
      TCoreMaskingselfTask tcmt = this.maskingSelfTaskService.queryMaskingTaskByID(taskid);
      TaskInfo ti = new TaskInfo();
      ti.setId(tcmt.getId());
      ti.setTaskname(tcmt.getTaskname());
      ti.setFdname(tcmt.getFdname());
      ti.setEngineid(tcmt.getEngineid());
      ti.setInserttype(tcmt.getInserttype());
      ti.setNote(tcmt.getNote());
      mi.setTaskInfo(ti);
      List<TCoreMaskingselfTable> siList = this.maskingSelfTaskService.queryMaskingTable(mi.getTaskInfo().getId(), "0");
      SourceInfo si = new SourceInfo();
      si.setDatasystemid(((TCoreMaskingselfTable)siList.get(0)).getDatasystemid());
      si.setDbschema(((TCoreMaskingselfTable)siList.get(0)).getDbschema());
      mi.setSourceInfo(si);
      List<String> tnList = new ArrayList();

      for(int i = 0; i < siList.size(); ++i) {
         tnList.add(((TCoreMaskingselfTable)siList.get(i)).getTablename());
      }

      String[] tablename = (String[])tnList.toArray(new String[tnList.size()]);
      mi.setCache(this.maskingSelfTaskService.queryMultiDBSourceMapping(mi.getTaskInfo().getId(), tablename));
      return mi;
   }

   @RequestMapping({"/executetask"})
   public String executetask(String taskid, HttpServletRequest request, HttpServletResponse response, Model model) {
      LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
      TCoreMaskingselfTask task = this.maskingSelfTaskService.queryMaskingTaskByID(taskid);
      this.infoSelfService.executeTask(taskid, loginUser.getTsysUser().getId());
      TConsoleLog record = new TConsoleLog();
      String username = loginUser.getTsysUser().getUsername();
      record.setModule("本库脱敏");
      record.setOperationtime(new Date());
      record.setUser(username);
      record.setLogmessage("执行本库脱敏任务");
      this.operationService.add(record);
      model.addAttribute("taskid", taskid);
      model.addAttribute("engineid", task.getEngineid());
      return "core/monitor/monitorselftask";
   }

   @RequestMapping({"/exerecord"})
   public String exerecord(String tasktype, String taskid, HttpServletRequest request, HttpServletResponse response, Model model) {
      model.addAttribute("taskid", taskid);
      return "core/maskingselftask/exerecord";
   }

   @RequestMapping({"/exerecordlog"})
   public String exerecordlog(String tasktype) {
      return "core/maskingselftask/detail/type/log";
   }

   @RequestMapping({"/queryTableColumName"})
   @ResponseBody
   public Map<Object, Object> queryTableColumName(@RequestParam Map<String, Object> map, String taskid, String sourceid) {
      return null;
   }

   @RequestMapping({"/querytaskrecord"})
   @ResponseBody
   public List<TaskRecordVO> querytaskrecord(String taskid, HttpServletRequest request, HttpServletResponse response, Model model) {
      List<TaskRecordVO> list = this.maskingTaskService.querytaskrecord(taskid);
      return list;
   }

   @RequestMapping({"/structure/querystructurebygroup"})
   @ResponseBody
   public List<TCoreFileStructure> querystructurebygroup(String groupname, String tableNamePattern) {
      return this.fileSystemService.queryStructureByGroup(groupname, tableNamePattern);
   }

   @RequestMapping({"/querytablerecord"})
   @ResponseBody
   public List<TCoreMaskingDetailrecord> querytablerecord(String recordid, HttpServletRequest request, HttpServletResponse response, Model model) {
      List<TCoreMaskingDetailrecord> record = this.maskingTaskService.querytablerecord(recordid);
      return record;
   }

   @RequestMapping({"/detailtype"})
   public String detailtype(String tasktype) {
      return "core/maskingselftask/detail/type/multi";
   }
}
