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

import com.chenyang.nse.bussiness.dao.PageInfo;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystem;
import com.chenyang.nse.bussiness.entity.orm.table.core.charts.TCoreChartsEight;
import com.chenyang.nse.bussiness.entity.orm.table.core.charts.TCoreChartsFive;
import com.chenyang.nse.bussiness.entity.orm.table.core.charts.TCoreChartsFour;
import com.chenyang.nse.bussiness.entity.orm.table.core.charts.TCoreChartsOne;
import com.chenyang.nse.bussiness.entity.orm.table.core.charts.TCoreChartsSeven;
import com.chenyang.nse.bussiness.entity.orm.table.core.charts.TCoreChartsSix;
import com.chenyang.nse.bussiness.entity.orm.table.core.charts.TCoreChartsThree;
import com.chenyang.nse.bussiness.entity.orm.table.core.charts.TCoreChartsTwo;
import com.chenyang.nse.bussiness.entity.orm.table.core.project.TCoreProjectInfo;
import com.chenyang.nse.bussiness.entity.vo.DataGridVO;
import com.chenyang.nse.bussiness.entity.vo.Releasecolumn;
import com.chenyang.nse.bussiness.service.console.UserService;
import com.chenyang.nse.bussiness.service.core.CoreProjectService;
import com.chenyang.nse.bussiness.service.core.DataSystemService;
import com.chenyang.nse.bussiness.tools.jdbc.JdbcTool;
import com.chenyang.nse.bussiness.tools.string.StringTool;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
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/projectInfo"})
public class ProjectInfoController {
   private static Logger logger = LoggerFactory.getLogger(ModifySubsetController.class);
   @Autowired
   private CoreProjectService coreProjectService;
   @Autowired
   private DataSystemService dataSystemService;
   @Autowired
   private UserService userService;

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

   @ResponseBody
   @RequestMapping({"/release"})
   public String release(String isall, String projectid, HttpServletRequest request, HttpServletResponse response, Model model) {
      long a1 = System.currentTimeMillis();
      List<Releasecolumn> releasecolumnslist = this.coreProjectService.queryTcoreReleasecolumn(projectid, projectid);
      if (releasecolumnslist.size() == 0) {
         return "1";
      } else {
         TCoreProjectInfo tCoreProjectInfo = this.coreProjectService.queryProjectByProjectId(projectid);
         tCoreProjectInfo.setUpdatetime(new Date());
         tCoreProjectInfo.setProgress("2");
         this.coreProjectService.update(tCoreProjectInfo);
         HashMap<String, Integer> map_rule = new HashMap();
         HashMap<String, Integer> map_t_rule = new HashMap();
         HashMap<String, Integer> map_table_schame = new HashMap();
         HashMap<String, Integer> map_notable_schame = new HashMap();
         Long num = new Long(0L);
         int num_seven_sure = 0;
         int num_seven_nosure = 0;
         int num_sensitive = 0;
         Set<String> set_datasystemid = new HashSet();
         Set<String> set_schame_name = new HashSet();
         Set<String> set_table_name = new HashSet();
         Set<String> set_rule_name = new HashSet();
         new ArrayList();
         HashMap<String, Releasecolumn> map_table_schame_d = new HashMap();
         HashMap<String, List<String>> tablemap = new HashMap();
         HashMap<String, List<String>> schamemap = new HashMap();
         new HashMap();

         for(Releasecolumn releasecolumn : releasecolumnslist) {
            num = num + 1L;
            String rulename = releasecolumn.getRulename();
            String schema = releasecolumn.getTschema();
            String tablename = releasecolumn.getTablename();
            String datasystemid = releasecolumn.getDatasystemid();
            String checked = releasecolumn.getChecked();
            String columnname = releasecolumn.getColumnname();
            set_schame_name.add(schema);
            set_table_name.add(tablename);
            set_datasystemid.add(datasystemid);
            String schema_table = datasystemid + "~" + schema + "~" + tablename;
            String schema_table_rulename = datasystemid + "~" + schema + "~" + tablename + "~" + rulename;
            String datasystemidAndSchema = datasystemid + "~" + schema;
            Integer num_r = (Integer)map_rule.get(rulename);
            map_rule.put(releasecolumn.getRulename(), num_r == null ? 1 : num_r + 1);
            map_table_schame_d.put(schema_table, releasecolumn);
            List<String> schame_name_list = (List)schamemap.get(datasystemid);
            if (schame_name_list == null) {
               schame_name_list = new ArrayList();
            }

            schame_name_list.add(schema);
            schamemap.put(datasystemid, schame_name_list);
            List<String> table_name_list = (List)schamemap.get(datasystemidAndSchema);
            if (table_name_list == null) {
               table_name_list = new ArrayList();
            }

            table_name_list.add(tablename);
            tablemap.put(datasystemidAndSchema, table_name_list);
            Integer num_t_r = (Integer)map_t_rule.get(schema_table_rulename);
            map_t_rule.put(schema_table_rulename, num_t_r == null ? 1 : num_t_r + 1);
            if (!releasecolumn.getRulename().equals("") && !releasecolumn.getRulename().equals("确认非敏感字段") && releasecolumn.getChecked().equals("1")) {
               ++num_seven_sure;
            }

            if (!releasecolumn.getRulename().equals("") && !releasecolumn.getRulename().equals("确认非敏感字段") && releasecolumn.getChecked().equals("0")) {
               ++num_seven_nosure;
            }

            if (!releasecolumn.getRulename().equals("") && !releasecolumn.getRulename().equals("确认非敏感字段")) {
               Integer num_eight_sure = (Integer)map_table_schame.get(schema_table);
               map_table_schame.put(schema_table, num_eight_sure == null ? 1 : num_eight_sure + 1);
               set_rule_name.add(rulename);
               ++num_sensitive;
            } else {
               Integer num_eight_nosure = (Integer)map_notable_schame.get(schema_table);
               map_notable_schame.put(schema_table, num_eight_nosure == null ? 1 : num_eight_nosure + 1);
            }
         }

         long a2 = System.currentTimeMillis();
         System.out.println("查询:" + (a2 - a1) / 1000L);
         List<String> datasystemid = new ArrayList(set_datasystemid);
         List<String> rule_name = new ArrayList(set_rule_name);
         this.coreProjectService.removeByProjectid(projectid);
         long a3 = System.currentTimeMillis();
         System.out.println("删除:" + (a3 - a1) / 1000L);
         this.savecharts_one(map_rule, projectid);
         long a4 = System.currentTimeMillis();
         System.out.println("任务1:" + (a4 - a1) / 1000L);
         this.savecharts_two(map_rule, projectid);
         long a5 = System.currentTimeMillis();
         System.out.println("任务2:" + (a5 - a1) / 1000L);
         this.savecharts_three(map_rule, num_sensitive, projectid);
         long a6 = System.currentTimeMillis();
         System.out.println("任务3:" + (a6 - a1) / 1000L);
         this.savecharts_five(map_rule, projectid);
         long a7 = System.currentTimeMillis();
         System.out.println("任务4:" + (a7 - a1) / 1000L);
         this.savecharts_six(map_table_schame.size(), map_table_schame_d.size() - map_table_schame.size(), projectid);
         long a8 = System.currentTimeMillis();
         System.out.println("任务5:" + (a8 - a1) / 1000L);
         this.savecharts_seven(num_seven_sure, num_seven_nosure, releasecolumnslist.size(), projectid);
         long a9 = System.currentTimeMillis();
         System.out.println("任务6:" + (a9 - a1) / 1000L);
         if (isall.equals("1")) {
            this.findtablenum(datasystemid, schamemap, tablemap, rule_name, map_table_schame, map_notable_schame, map_t_rule, projectid);
         }

         long a10 = System.currentTimeMillis();
         System.out.println("任务7:" + (a10 - a1) / 1000L);
         tCoreProjectInfo.setProgress("1");
         this.coreProjectService.update(tCoreProjectInfo);
         return "0";
      }
   }

   public void savecharts_one(HashMap<String, Integer> map_rule, String projectid) {
      for(Map.Entry<String, Integer> entry : map_rule.entrySet()) {
         if (!((String)entry.getKey()).equals("")) {
            TCoreChartsOne tCoreChartsOne = new TCoreChartsOne();
            tCoreChartsOne.setProjectid(projectid);
            tCoreChartsOne.setRulecolumnum((Integer)entry.getValue());
            tCoreChartsOne.setRulename((String)entry.getKey());
            this.coreProjectService.saveTCoreChartsOne(tCoreChartsOne);
         }
      }

   }

   public void savecharts_two(HashMap<String, Integer> map_rule, String projectid) {
      double i = (double)0.0F;

      for(Map.Entry<String, Integer> entry : map_rule.entrySet()) {
         if (!((String)entry.getKey()).equals("") && !((String)entry.getKey()).equals("确认非敏感字段")) {
            ++i;
         }
      }

      TCoreChartsTwo tCoreChartsTwo = new TCoreChartsTwo();
      tCoreChartsTwo.setProjectid(projectid);
      int nosensitiveruleaccounted = 0;
      double sensitiveruleaccounted = (double)0.0F;
      if (map_rule.entrySet().size() != 0) {
         sensitiveruleaccounted = i / (double)map_rule.entrySet().size();
      }

      BigDecimal b = new BigDecimal(sensitiveruleaccounted);
      double f1 = b.setScale(2, 4).doubleValue();
      int f2 = 0;
      if (f1 < (double)1.0F) {
         f2 = 1;
      }

      f2 = (int)Math.round(f1);
      nosensitiveruleaccounted = 100 - f2;
      tCoreChartsTwo.setProjectid(projectid);
      tCoreChartsTwo.setNosensitiveruleaccounted(String.valueOf(nosensitiveruleaccounted));
      tCoreChartsTwo.setSensitiveruleaccounted(String.valueOf(f2));
      this.coreProjectService.saveTCoreChartsTwo(tCoreChartsTwo);
   }

   public void savecharts_three(HashMap<String, Integer> map_rule, int count, String projectid) {
      for(Map.Entry<String, Integer> entry : map_rule.entrySet()) {
         if (!((String)entry.getKey()).equals("") && !((String)entry.getKey()).equals("确认非敏感字段")) {
            TCoreChartsThree tCoreChartsThree = new TCoreChartsThree();
            tCoreChartsThree.setProjectid(projectid);
            tCoreChartsThree.setRuleaccounted((Integer)entry.getValue() * 100 / count);
            tCoreChartsThree.setRulename((String)entry.getKey());
            this.coreProjectService.saveTCoreChartsThree(tCoreChartsThree);
         }
      }

   }

   public void savecharts_four(HashMap<String, Double> map_rule, String projectid) {
      for(Map.Entry<String, Double> entry : map_rule.entrySet()) {
         if (!((String)entry.getKey()).equals("")) {
            TCoreChartsFour tCoreChartsFour = new TCoreChartsFour();
            tCoreChartsFour.setProjectid(projectid);
            tCoreChartsFour.setRulecolumnum((Double)entry.getValue());
            tCoreChartsFour.setRulename((String)entry.getKey());
            this.coreProjectService.saveTCoreChartsFour(tCoreChartsFour);
         }
      }

   }

   public void savecharts_five(HashMap<String, Integer> map_rule, String projectid) {
      for(Map.Entry<String, Integer> entry : map_rule.entrySet()) {
         if (!((String)entry.getKey()).equals("")) {
            TCoreChartsFive tCoreChartsFive = new TCoreChartsFive();
            tCoreChartsFive.setProjectid(projectid);
            tCoreChartsFive.setRulecolumnum((long)(Integer)entry.getValue());
            tCoreChartsFive.setRulename((String)entry.getKey());
            this.coreProjectService.saveTCoreChartsFive(tCoreChartsFive);
         }
      }

   }

   public void savecharts_six(Integer sensitivenum, Integer nosensitivenum, String projectid) {
      TCoreChartsSix tCoreChartsSix = new TCoreChartsSix();
      tCoreChartsSix.setProjectid(projectid);
      tCoreChartsSix.setSensitivenum(sensitivenum);
      tCoreChartsSix.setNosensitivenum(nosensitivenum);
      this.coreProjectService.saveTCoreChartsSix(tCoreChartsSix);
   }

   public void savecharts_seven(Integer sure_count, Integer no_sure_count, Integer all_count, String projectid) {
      TCoreChartsSeven tCoreChartsSeven = new TCoreChartsSeven();
      tCoreChartsSeven.setProjectid(projectid);
      sure_count = sure_count * 100 / all_count;
      no_sure_count = no_sure_count * 100 / all_count;
      tCoreChartsSeven.setNosurecolumnum(no_sure_count);
      tCoreChartsSeven.setSurecolumnum(sure_count);
      this.coreProjectService.saveTCoreChartsSeven(tCoreChartsSeven);
   }

   public void savecharts_eight(double all_num, double all_nonum, String projectid) {
      TCoreChartsEight tCoreChartsEight = new TCoreChartsEight();
      tCoreChartsEight.setProjectid(projectid);
      tCoreChartsEight.setNosurecolumnum(String.valueOf(all_nonum));
      tCoreChartsEight.setAllcolumnum(String.valueOf(all_nonum + all_num));
      tCoreChartsEight.setSurecolumnum(String.valueOf(all_num));
      this.coreProjectService.saveTCoreChartsEight(tCoreChartsEight);
   }

   public void findtablenum(List<String> datasystemid, HashMap<String, List<String>> schamemap, HashMap<String, List<String>> tablemap, List<String> rulelist, HashMap<String, Integer> map_table_schame, HashMap<String, Integer> map_notable_schame, HashMap<String, Integer> map_t_rule, String projectid) {
      double all_num = (double)0.0F;
      double all_nonum = (double)0.0F;
      HashMap<String, Double> map_rule = new HashMap();

      for(int i = 0; i < datasystemid.size(); ++i) {
         String datasystemid_map_key = (String)datasystemid.get(i);
         List<String> schamelist = (List)schamemap.get(datasystemid_map_key);
         TCoreDatasystem datasystem = this.dataSystemService.queryDataSystemById((String)datasystemid.get(i));
         if (datasystem != null) {
            this.iskeberos(datasystem);
            Connection conn = JdbcTool.getConnection(datasystem);

            try {
               for(int j = 0; j < schamelist.size(); ++j) {
                  String schame_map_key = (String)schamelist.get(j);
                  List<String> tablelist = (List)tablemap.get(datasystemid_map_key + "~" + schame_map_key);

                  for(int k = 0; k < tablelist.size(); ++k) {
                     String table_map_key = (String)tablelist.get(k);
                     double coutnum = (double)0.0F;
                     String sql = "select count(0) as count from " + schame_map_key + "." + table_map_key;
                     PreparedStatement statement = conn.prepareStatement(sql);

                     ResultSet resultSet;
                     for(resultSet = statement.executeQuery(); resultSet.next(); coutnum = resultSet.getDouble("count")) {
                     }

                     resultSet.close();
                     statement.close();

                     for(String rulename : rulelist) {
                        Integer num = (Integer)map_t_rule.get(datasystemid_map_key + "~" + schame_map_key + "~" + table_map_key + "~" + rulename);
                        if (num == null) {
                           num = 0;
                        }

                        Double map_rule_num = (Double)map_rule.get(rulename);
                        if (map_rule_num == null) {
                           map_rule_num = (double)0.0F;
                        }

                        map_rule_num = map_rule_num + coutnum * (double)num;
                        map_rule.put(rulename, map_rule_num);
                     }

                     Integer count = (Integer)map_table_schame.get((String)datasystemid.get(i) + "~" + (String)schamelist.get(j) + "~" + (String)tablelist.get(k));
                     Integer nocount = (Integer)map_notable_schame.get((String)datasystemid.get(i) + "~" + (String)schamelist.get(j) + "~" + (String)tablelist.get(k));
                     if (count != null) {
                        all_num += coutnum * (double)count;
                        all_nonum += coutnum * (double)nocount;
                     }
                  }
               }
            } catch (Exception e) {
               System.out.println(e.getMessage());
               e.printStackTrace();
            }

            try {
               conn.close();
            } catch (SQLException e) {
               e.printStackTrace();
            }
         }
      }

      this.savecharts_eight(all_num, all_nonum, projectid);
      this.savecharts_four(map_rule, projectid);
   }

   @RequestMapping({"/validateProjectName"})
   @ResponseBody
   public String validateProjectName(String value, HttpServletRequest request, HttpServletResponse response, Model model) {
      List<TCoreProjectInfo> list = this.coreProjectService.query("");
      List<String> linkname = new ArrayList();

      for(TCoreProjectInfo tCoreProjectInfo : list) {
         linkname.add(tCoreProjectInfo.getProjectname());
      }

      return linkname.contains(value) ? "0" : "1";
   }

   @RequestMapping({"/add"})
   public void add(TCoreProjectInfo datasource, HttpServletRequest request, HttpServletResponse response, Model model) {
      Date date = new Date();
      datasource.setId(UUID.randomUUID().toString());
      datasource.setCreatetime(date);
      List<String> list_table = JdbcTool.sql_insert_q(new Releasecolumn());
      String hanziToPinyinFirst = StringTool.hanziToPinyinFirst(datasource.getProjectname());
      String taleName = "p_" + hanziToPinyinFirst + "_" + date.getTime();
      datasource.setRealprojectname(taleName);
      datasource.setProgress("0");
      this.coreProjectService.save(datasource);
      StringBuilder sqlstr = new StringBuilder("CREATE TABLE " + taleName + "(");

      for(String coulmname : list_table) {
         sqlstr.append(coulmname + " varchar(100),");
      }

      sqlstr.append(" PRIMARY KEY (id))");
      sqlstr.append(" ENGINE=InnoDB DEFAULT CHARSET=utf8");
      System.out.println(sqlstr.toString());
      this.coreProjectService.createsqlstr(sqlstr);
   }

   @RequestMapping({"/remove"})
   @ResponseBody
   public Integer remove(String id, HttpServletRequest request, HttpServletResponse response, Model model) {
      List<TCoreProjectInfo> list = this.coreProjectService.queryById(id);
      String projectname = ((TCoreProjectInfo)list.get(0)).getRealprojectname();
      StringBuilder sqlstr = new StringBuilder("drop table " + projectname);
      this.coreProjectService.createsqlstr(sqlstr);
      this.coreProjectService.remove(id);
      this.coreProjectService.removeAllChat(projectname);
      return 0;
   }

   @ResponseBody
   @RequestMapping({"/queryAll"})
   public DataGridVO<TCoreProjectInfo> query(PageInfo pageInfo, String projectname, int rows, int page, HttpServletRequest request, HttpServletResponse response, Model model) {
      pageInfo.setPageno(page);
      pageInfo.setPagesize(rows);
      List<TCoreProjectInfo> list = this.coreProjectService.queryAll(pageInfo, projectname);
      DataGridVO<TCoreProjectInfo> vo = new DataGridVO<TCoreProjectInfo>(pageInfo.getCount(), list);
      return vo;
   }

   public void iskeberos(TCoreDatasystem datasystem) {
      if ("HIVE".equals(datasystem.getDbtype()) && "on".equals(datasystem.getIskerberos())) {
         System.setProperty("java.security.krb5.conf", datasystem.getXmlpath() + "/krb5.conf");
      }

   }
}
