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

import com.alibaba.fastjson.JSON;
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.discovery.TcoreDiscoveryCondition;
import com.chenyang.nse.bussiness.entity.orm.table.core.discovery.TcoreDiscoverySensitivecolumn;
import com.chenyang.nse.bussiness.entity.orm.table.core.discovery.TcoreDiscoveryTask;
import com.chenyang.nse.bussiness.entity.orm.table.core.discovery.TcoreDiscoveryVersrion;
import com.chenyang.nse.bussiness.entity.vo.DataGridVO;
import com.chenyang.nse.bussiness.entity.vo.DiscoverytaskVO;
import com.chenyang.nse.bussiness.entity.vo.ResultVO;
import com.chenyang.nse.bussiness.service.console.OperationService;
import com.chenyang.nse.bussiness.service.core.DataSystemService;
import com.chenyang.nse.bussiness.service.core.DiscoveryConditionService;
import com.chenyang.nse.bussiness.service.core.DiscoverySensitivecolumnService;
import com.chenyang.nse.bussiness.service.core.DiscoveryVersrionService;
import com.chenyang.nse.bussiness.service.core.dataproject.DiscoverytaskService;
import com.chenyang.nse.bussiness.service.redis.RedisService;
import com.chenyang.nse.bussiness.tools.office.ExcelTool;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({"/core/discoverytask"})
public class DiscoverytaskController {
   @Autowired
   private DiscoverytaskService discoverytaskService;
   @Autowired
   private DiscoveryVersrionService discoveryVersrionService;
   @Autowired
   private DiscoverySensitivecolumnService discoverySensitivecolumnService;
   @Autowired
   private DiscoveryConditionService discoveryConditionService;
   @Autowired
   private DataSystemService dataSystemService;
   @Autowired
   private OperationService operationService;
   @Autowired
   private RedisService redisService;

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

   @RequestMapping({"/discoverytasklog"})
   public String discoverytasklog(String taskid, String taskname, HttpServletRequest request, HttpServletResponse response, Model model) {
      model.addAttribute("taskname", taskname);
      model.addAttribute("taskid", taskid);
      return "core/discoverytask/discoverytasklog";
   }

   @RequestMapping({"/discoverytaskdetail"})
   public String discoverytaskdetail(String taskid, String taskname, HttpServletRequest request, HttpServletResponse response, Model model) {
      model.addAttribute("taskid", taskid);
      TcoreDiscoveryTask task = this.discoverytaskService.get(taskid);
      List<TcoreDiscoveryVersrion> list = this.discoveryVersrionService.queryTcoreDiscoveryVersriont(taskid, task.getCurversion());
      List<TcoreDiscoveryCondition> listparam = this.discoveryConditionService.queryDiscoveryConditionByTaskId(taskid);
      HashMap<String, String> hm = new HashMap();
      hm.put("datasystemid", "");
      hm.put("table", "");
      hm.put("maxRowCount", "");
      hm.put("rate", "");
      hm.put("typelist", "");
      hm.put("type", "");
      hm.put("caijitype", "");
      hm.put("databasename", "");
      hm.put("datasourcetype", "");
      List<String> liststr = new ArrayList();
      HashMap<String, String> datasourcetype = new HashMap();
      datasourcetype.put("1", "关系型数据库");
      datasourcetype.put("2", "数据文件");
      datasourcetype.put("3", "hadoop");

      for(TcoreDiscoveryCondition log : listparam) {
         switch (log.getParameterid()) {
            case 1:
               hm.put("datasystemid", log.getParametercontent());
               TCoreDatasystem tcoreDatasystem = this.dataSystemService.queryDataSystemById(log.getParametercontent());
               if ("1".equals(task.getIsdmpflag())) {
                  hm.put("datasourcetype", datasourcetype.get(task.getIsdmpflag()));
                  hm.put("databasename", "ORACLE-DMP");
               } else {
                  hm.put("datasourcetype", datasourcetype.get(tcoreDatasystem.getFlag()));
                  hm.put("databasename", tcoreDatasystem.getDbtype());
               }
               break;
            case 2:
               hm.put("table", log.getParametercontent());
               break;
            case 3:
               hm.put("maxRowCount", log.getParametercontent());
               break;
            case 4:
               hm.put("rate", log.getParametercontent());
               break;
            case 5:
               liststr.add(log.getParametercontent());
            case 6:
            case 7:
            case 9:
            case 10:
            default:
               break;
            case 8:
               hm.put("type", log.getParametercontent());
               break;
            case 11:
               hm.put("caijitype", log.getParametercontent());
         }
      }

      hm.put("taskname", task.getTname());
      hm.put("createtime", ((TcoreDiscoveryVersrion)list.get(0)).getCreatetime().toString());
      hm.put("username", ((TcoreDiscoveryVersrion)list.get(0)).getUsername());
      model.addAttribute("task", hm);
      model.addAttribute("tasklist", liststr);
      return "core/discoverytask/discoverytaskdetail";
   }

   @ResponseBody
   @RequestMapping({"/discoverytaskdetaillist"})
   public List<Map<String, Object>> discoverytaskdetaillist(String taskid, Integer page, Integer rows, HttpServletRequest request, HttpServletResponse response, Model model) {
      List<Map<String, Object>> sensitiveDataList = new ArrayList();
      TcoreDiscoveryTask task = this.discoverytaskService.get(taskid);
      Map<String, List<TcoreDiscoverySensitivecolumn>> tablemap = new HashMap();
      int k = 0;
      String prefix = "";

      for(TcoreDiscoverySensitivecolumn tcoreDiscoverySensitivecolumn : this.discoverySensitivecolumnService.querySensitiveColumnsByGroupIdByVersion(taskid, task.getCurversion())) {
         if (k == 0) {
            if ("1".equals(task.getIsdmpflag())) {
               prefix = "";
            } else {
               TCoreDatasystem system = this.dataSystemService.queryDataSystemById(tcoreDiscoverySensitivecolumn.getDatasourceid());
               if (system.getFlag().equals("2")) {
                  prefix = "";
               } else {
                  prefix = tcoreDiscoverySensitivecolumn.getTschema() + ".";
               }
            }
         } else if (!prefix.equals("")) {
            prefix = tcoreDiscoverySensitivecolumn.getTschema() + ".";
         }

         String schematable = prefix + tcoreDiscoverySensitivecolumn.getTablename();
         List<TcoreDiscoverySensitivecolumn> ls = new ArrayList();
         if (tablemap.get(schematable) == null) {
            ls.add(tcoreDiscoverySensitivecolumn);
         } else {
            ls = (List)tablemap.get(schematable);
            ls.add(tcoreDiscoverySensitivecolumn);
         }

         ++k;
         tablemap.put(schematable, ls);
      }

      int i = 0;

      for(Map.Entry<String, List<TcoreDiscoverySensitivecolumn>> entry : tablemap.entrySet()) {
         String tableName = (String)entry.getKey();
         Map<String, Object> table = new HashMap();
         ++i;
         table.put("id", i + "");
         table.put("name", tableName);
         List<Map<String, String>> childmap = new ArrayList();
         int sensitiveColumnCount = 0;

         List<TcoreDiscoverySensitivecolumn> listNew = (List)entry.getValue();
         for(TcoreDiscoverySensitivecolumn column : listNew) {
            Map<String, String> map = new HashMap();
            if (null != column.getRegextype() && !column.getRegextype().equals("确认非敏感字段") && !column.getRegextype().equals("") && !column.getRegextype().equals("null")) {
               ++sensitiveColumnCount;
            }

            map.put("id", i + "_" + sensitiveColumnCount);
            map.put("name", column.getColumnname());
            map.put("parentname", column.getTablename());
            map.put("regexType", column.getRegextype());
            map.put("ruleName", column.getRulename());
            map.put("columnChecked", column.getChecked());
            map.put("sampling", column.getSampling());
            map.put("etsampling", column.getEtsampling());
            map.put("mate", column.getMate());
            map.put("materatio", column.getMateratio());
            childmap.add(map);
         }

         table.put("children", childmap);
         if (sensitiveColumnCount > 0) {
            table.put("regexType", sensitiveColumnCount + "个敏感字段");
         }

         sensitiveDataList.add(table);
      }

      return sensitiveDataList;
   }

   @ResponseBody
   @RequestMapping({"/discoverytasklist"})
   public DataGridVO<DiscoverytaskVO> discoverytasklist(PageInfo pageInfo, String taskname, Integer page, Integer rows, HttpServletRequest request, HttpServletResponse response, Model model) {
      pageInfo.setPageno(page);
      pageInfo.setPagesize(rows);
      HashMap<String, String> map = new HashMap();
      map.put("tname", taskname);
      List<DiscoverytaskVO> list = this.discoverytaskService.queryDiscoverytaskVO(pageInfo, map);
      DataGridVO<DiscoverytaskVO> vo = new DataGridVO<DiscoverytaskVO>(pageInfo.getCount(), list);
      return vo;
   }

   @ResponseBody
   @RequestMapping({"/discoverytaskloglist"})
   public DataGridVO<TcoreDiscoveryVersrion> discoverytaskloglist(String taskid, Integer page, Integer rows, HttpServletRequest request, HttpServletResponse response, Model model) {
      PageInfo pageInfo = new PageInfo();
      pageInfo.setPageno(page);
      pageInfo.setPagesize(rows);
      List<TcoreDiscoveryVersrion> list = this.discoveryVersrionService.queryTcoreDiscoveryVersriont(pageInfo, taskid);
      DataGridVO<TcoreDiscoveryVersrion> vo = new DataGridVO<TcoreDiscoveryVersrion>((long)list.size(), list);
      return vo;
   }

   @ResponseBody
   @RequestMapping({"/updateisrelease"})
   public void updateisrelease(String id) {
      this.discoverytaskService.updateisrelease(id);
   }

   @ResponseBody
   @RequestMapping({"/deleteDiscoverytask"})
   public void deleteDiscoverytask(HttpServletRequest request, String id, String tname) {
      TConsoleLog record = new TConsoleLog();
      LoginUser user = (LoginUser)request.getSession().getAttribute("loginUser");
      String username = user.getTsysUser().getUsername();
      record.setUser(username);
      record.setLogmessage("删除敏感数据发现任务");
      record.setModule("敏感数据发现");
      record.setOperationObject(tname);
      record.setOperationtime(new Date());
      TcoreDiscoveryTask task = this.discoverytaskService.get(id);
      record.setOperationObject(task.getTname());
      this.operationService.add(record);
      this.discoverytaskService.deleteDiscoverytask(id, task.getResultid());
      this.redisService.remove(id + "tableCount");
      this.redisService.remove(id + "tableSum");
      this.redisService.remove("taskstatus_" + id);
   }

   @ResponseBody
   @RequestMapping({"/exportToExceltoLog"})
   public ResultVO exportToExceltoLog(String groupid, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
      String path = request.getSession().getServletContext().getRealPath("/") + "css" + File.separator + UUID.randomUUID().toString() + ".xlsx";
      LinkedBlockingQueue<HashMap<String, String>> queue = new LinkedBlockingQueue();
      new ArrayList();
      String version = "";
      TcoreDiscoveryTask tcoreDiscoveryTask = this.discoverytaskService.get(groupid);
      version = tcoreDiscoveryTask.getCurversion();
      List<TcoreDiscoverySensitivecolumn> sensitiveColumns = this.discoverySensitivecolumnService.querySensitiveColumnsByGroupIdByVersion(groupid, version);
      Collections.sort(sensitiveColumns, new Comparator<TcoreDiscoverySensitivecolumn>() {
         public int compare(TcoreDiscoverySensitivecolumn s1, TcoreDiscoverySensitivecolumn s2) {
            if (s1.getTablename().compareTo(s2.getTablename()) < 0) {
               return -1;
            } else {
               return s1.getTablename().compareTo(s2.getTablename()) == 0 ? 0 : 1;
            }
         }
      });

      for(TcoreDiscoverySensitivecolumn tcoreDiscoverySensitivecolumn : sensitiveColumns) {
         try {
            HashMap<String, String> hashmap = new HashMap();
            hashmap.put("id", tcoreDiscoverySensitivecolumn.getGroupid());
            hashmap.put("taskversion", tcoreDiscoverySensitivecolumn.getTaskversion());
            hashmap.put("datasourcename", tcoreDiscoverySensitivecolumn.getNote());
            hashmap.put("schema", tcoreDiscoverySensitivecolumn.getTschema());
            hashmap.put("parentname", tcoreDiscoverySensitivecolumn.getTablename());
            hashmap.put("name", tcoreDiscoverySensitivecolumn.getColumnname());
            hashmap.put("totalCount", tcoreDiscoverySensitivecolumn.getSampling());
            hashmap.put("validCount", tcoreDiscoverySensitivecolumn.getEtsampling());
            hashmap.put("matchCount", tcoreDiscoverySensitivecolumn.getMate());
            hashmap.put("matchRate", tcoreDiscoverySensitivecolumn.getMateratio());
            hashmap.put("regexType", tcoreDiscoverySensitivecolumn.getRegextype());
            hashmap.put("ruleName", tcoreDiscoverySensitivecolumn.getRulename());
            hashmap.put("checked", tcoreDiscoverySensitivecolumn.getChecked().equals("1") ? "是" : "否");
            hashmap.put("issmart", tcoreDiscoverySensitivecolumn.getIsIntelligent().equals("1") ? "是" : "否");
            queue.put(hashmap);
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }

      Map<String, String> titlevalue = new LinkedHashMap();
      titlevalue.put("发现任务ID", "id");
      titlevalue.put("版本号", "taskversion");
      titlevalue.put("数据源", "datasourcename");
      titlevalue.put("所有者", "schema");
      titlevalue.put("表名", "parentname");
      titlevalue.put("列名", "name");
      titlevalue.put("取样", "totalCount");
      titlevalue.put("有效取样", "validCount");
      titlevalue.put("匹配", "matchCount");
      titlevalue.put("匹配率", "matchRate");
      titlevalue.put("敏感类型", "regexType");
      titlevalue.put("脱敏规则", "ruleName");
      titlevalue.put("是否已确认", "checked");
      titlevalue.put("是否智能记忆", "issmart");
      List<Integer> columnWidthList = new ArrayList();
      columnWidthList.add(2200);
      columnWidthList.add(2200);
      columnWidthList.add(2200);
      columnWidthList.add(2200);
      columnWidthList.add(1600);
      columnWidthList.add(1600);
      columnWidthList.add(1600);
      columnWidthList.add(2700);
      columnWidthList.add(1600);
      columnWidthList.add(2200);
      columnWidthList.add(2700);
      columnWidthList.add(2700);
      columnWidthList.add(1600);
      columnWidthList.add(1600);
      ExcelTool.generateExcel(path, queue, titlevalue, columnWidthList, (List)null);
      ResultVO vo = new ResultVO(path, true);
      return vo;
   }

   @ResponseBody
   @RequestMapping({"/queryAllTableInforZuoYou"})
   public void queryAllTableInforZuoYou(@RequestParam Map<String, Object> parameter, HttpServletRequest request, HttpServletResponse response) {
      PrintWriter writer = null;
      String groupid = (String)parameter.get("groupid");
      String version = (String)parameter.get("version");
      String state = (String)parameter.get("state");
      if (state.equals("2")) {
         List<TcoreDiscoverySensitivecolumn> listyou = (List)request.getSession().getAttribute("list");

         try {
            request.setCharacterEncoding("utf8");
            response.setCharacterEncoding("utf8");
            response.setContentType("text/json; charset=utf-8");
            writer = response.getWriter();
            writer.print(JSON.toJSON(listyou));
         } catch (Exception e) {
            e.printStackTrace();
         }
      } else if (state.equals("1")) {
         List<TcoreDiscoverySensitivecolumn> listlishi = this.discoverySensitivecolumnService.querySensitiveColumnsByGroupIdByVersion(groupid, version);
         TcoreDiscoveryTask task = this.discoverytaskService.get(groupid);
         List<TcoreDiscoverySensitivecolumn> listnew = this.discoverySensitivecolumnService.querySensitiveColumnsByGroupIdByVersion(groupid, task.getCurversion());
         List<TcoreDiscoverySensitivecolumn> listzuo = new ArrayList();
         List<TcoreDiscoverySensitivecolumn> listyou = new ArrayList();
         new ArrayList();
         listzuo.addAll(listnew);
         boolean flag = false;
         int zuixincout = listnew.size();
         int lishicout = listlishi.size();

         for(int i = 0; i < listnew.size(); ++i) {
            for(int j = 0; j < listlishi.size(); ++j) {
               flag = false;
               String tablenew = ((TcoreDiscoverySensitivecolumn)listnew.get(i)).getTschema() + ((TcoreDiscoverySensitivecolumn)listnew.get(i)).getTablename() + ((TcoreDiscoverySensitivecolumn)listnew.get(i)).getColumnname();
               String tablelishi = ((TcoreDiscoverySensitivecolumn)listlishi.get(j)).getTschema() + ((TcoreDiscoverySensitivecolumn)listlishi.get(j)).getTablename() + ((TcoreDiscoverySensitivecolumn)listlishi.get(j)).getColumnname();
               if (tablenew.equals(tablelishi)) {
                  flag = true;
                  listyou.add(listlishi.get(j));
                  listlishi.remove(j);
                  break;
               }
            }

            if (!flag) {
               TcoreDiscoverySensitivecolumn k = new TcoreDiscoverySensitivecolumn();
               listyou.add(k);
            }
         }

         for(int i = 0; i < listlishi.size(); ++i) {
            TcoreDiscoverySensitivecolumn k = new TcoreDiscoverySensitivecolumn();
            listzuo.add(k);
            listyou.add(listlishi.get(i));
         }

         request.getSession().setAttribute("list", listyou);

         try {
            request.setCharacterEncoding("utf8");
            response.setCharacterEncoding("utf8");
            response.setContentType("text/json; charset=utf-8");
            writer = response.getWriter();
            if (state.equals("1")) {
               writer.print(JSON.toJSON(listzuo));
            } else {
               writer.print(JSON.toJSON(listyou));
            }
         } catch (Exception e) {
            e.printStackTrace();
         }
      }

   }
}
