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

import com.chenyang.nse.bussiness.entity.cache.LoginUser;
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.datamap.TCoreDatamap;
import com.chenyang.nse.bussiness.entity.orm.table.core.datamap.TCoreDatamapColumn;
import com.chenyang.nse.bussiness.entity.orm.table.core.datamap.TCoreDatamapTable;
import com.chenyang.nse.bussiness.entity.orm.table.core.datamap.TCoreDatamapTablealias;
import com.chenyang.nse.bussiness.entity.orm.table.core.datamap.TCoreDatamapTablerelation;
import com.chenyang.nse.bussiness.entity.orm.table.core.datamap.TCoreDatamapUsermap;
import com.chenyang.nse.bussiness.entity.orm.table.core.masking.TCoreMaskingTask;
import com.chenyang.nse.bussiness.entity.param.datamap.SaveNoteParam;
import com.chenyang.nse.bussiness.entity.vo.TreeVO;
import com.chenyang.nse.bussiness.entity.vo.datamap.DataMapVO;
import com.chenyang.nse.bussiness.enumeration.EdataSystem;
import com.chenyang.nse.bussiness.enumeration.EdataSystemGrade;
import com.chenyang.nse.bussiness.service.core.DataMapService;
import com.chenyang.nse.bussiness.service.core.DataSystemService;
import com.chenyang.nse.bussiness.service.core.EngineService;
import com.chenyang.nse.bussiness.tools.jdbc.JdbcTool;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({"/core/datamap"})
public class DataMapController {
   @Autowired
   private DataMapService dataMapService;
   @Autowired
   private DataSystemService dataSystemService;
   @Autowired
   private EngineService engineService;

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

   @ResponseBody
   @RequestMapping({"/inittree"})
   public List<TreeVO> inittree(String usermap, String code, String text, String parentid, HttpServletRequest request, HttpServletResponse response, Model model) {
      if (null == code || "".equals(code)) {
         code = EdataSystemGrade.DATASYSTEM.getCode();
      }

      LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
      List<TreeVO> datasystemtree = null;
      if (usermap == null || "0".equals(usermap)) {
         datasystemtree = this.dataMapService.initTree(EdataSystem.DATASYSTEM.getFlag(), code, text, parentid, "1", loginUser.getTsysUser().getId());
      }

      if ("1".equals(usermap)) {
         datasystemtree = this.dataMapService.initUserTree(EdataSystem.DATASYSTEM.getFlag(), code, text, parentid, "1", loginUser.getTsysUser().getId());
      }

      return datasystemtree;
   }

   @ResponseBody
   @RequestMapping({"/inittreeschema"})
   public List<TreeVO> inittreeschema(HttpServletRequest request, HttpServletResponse response, Model model) {
      List<TreeVO> datasystemtree = this.dataSystemService.initTreeSchema();
      return datasystemtree;
   }

   @ResponseBody
   @RequestMapping({"/testdatamap"})
   public Map<String, String> testdatamap(String datasystemid, String schemaname, HttpServletRequest request, HttpServletResponse response, Model model) {
      Map<String, String> vo = new HashMap();
      TCoreDatamap datamap = this.dataMapService.queryDataMapUnique(datasystemid, schemaname);
      if (datamap != null) {
         vo.put("result", Boolean.TRUE.toString());
      } else {
         vo.put("result", Boolean.FALSE.toString());
      }

      return vo;
   }

   @ResponseBody
   @RequestMapping({"/queryusermap"})
   public List<String> queryusermap(HttpServletRequest request, HttpServletResponse response, Model model) {
      List<String> idlist = new ArrayList();
      return idlist;
   }

   @ResponseBody
   @RequestMapping({"/generaterelation"})
   public void generatedatamap(String datasystemid, String schema, HttpServletRequest request, HttpServletResponse response, Model model) {
      this.dataMapService.removeDataMap(datasystemid, schema);
      this.dataMapService.generateDataMap(datasystemid, schema);
   }

   @ResponseBody
   @RequestMapping({"/showdatamap"})
   public DataMapVO showdatamap(String datasystemid, String schema, String usermap, HttpServletRequest request, HttpServletResponse response, Model model) {
      TCoreDatamap dataMap = this.dataMapService.queryDataMapUnique(datasystemid, schema);
      if (dataMap == null) {
         return null;
      } else {
         List<TCoreDatamapTable> table = null;
         if (usermap != null && "1".equals(usermap)) {
            LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
            if (loginUser == null || loginUser.getTsysUser() == null) {
               return null;
            }

            table = this.dataMapService.queryDataMapUserTable(dataMap.getId(), loginUser.getTsysUser().getId());
         } else {
            table = this.dataMapService.queryDataMapTable(dataMap.getId());
         }

         if (table != null && table.size() != 0) {
            List<TCoreDatamapTablerelation> relation = this.dataMapService.queryDataMapTableRelation(dataMap.getId());
            String pkcount = null;
            if (relation != null && relation.size() > 0) {
               pkcount = String.valueOf(relation.size());
            }

            DataMapVO vo = new DataMapVO(String.valueOf(table.size()), pkcount, table, relation);
            return vo;
         } else {
            return null;
         }
      }
   }

   @ResponseBody
   @RequestMapping({"/settablenodealias"})
   public TCoreDatamapTablealias settablenodealias(String datasystemid, String schema, String table, String alias, HttpServletRequest request, HttpServletResponse response, Model model) {
      TCoreDatamapTablealias tableAlias = this.dataMapService.setTableAlias(datasystemid, schema, table, alias);
      this.dataMapService.synchronizeDataMapTableAlias(tableAlias);
      return tableAlias;
   }

   @ResponseBody
   @RequestMapping({"/querytablerelation"})
   public TCoreDatamapTable querytablerelation(String datasystemid, String schema, String table, String treeid, HttpServletRequest request, HttpServletResponse response, Model model) {
      TCoreDatamapTable dataMapTable = this.dataMapService.queryDataMapTable(datasystemid, schema, table);
      return dataMapTable;
   }

   @ResponseBody
   @RequestMapping({"/querytablerelationbyid"})
   public TCoreDatamapTable querytablerelationbyid(String id, HttpServletRequest request, HttpServletResponse response, Model model) {
      TCoreDatamapTable tr = this.dataMapService.queryDataMapTableById(id);
      return tr;
   }

   @RequestMapping({"/tabledatacopy"})
   public String tabledatacopy(String step, String id, String datasystemid, String schema, String taskid, String execost, HttpServletRequest request, HttpServletResponse response, Model model) {
      model.addAttribute("tableid", id);
      return "core/datamap/tabledatacopy";
   }

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

   @ResponseBody
   @RequestMapping({"/querycoluminfo"})
   public List<TCoreDatamapColumn> querycoluminfo(String tablerelationid, HttpServletRequest request, HttpServletResponse response, Model model) {
      return this.dataMapService.queryDataMapColumnById(tablerelationid);
   }

   @ResponseBody
   @RequestMapping({"/queryrelationtablename"})
   public List<TCoreDatamapTable> queryrelationtablename(String datasystemid, String schema, String tablename, String usermap, HttpServletRequest request, HttpServletResponse response, Model model) {
      TCoreDatamap dataMap = this.dataMapService.queryDataMapUnique(datasystemid, schema);
      if (dataMap == null) {
         return null;
      } else {
         List<TCoreDatamapTable> list = null;
         if (usermap != null && "1".equals(usermap)) {
            LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
            if (loginUser == null || loginUser.getTsysUser() == null) {
               return null;
            }

            list = this.dataMapService.queryDataMapUserTable(dataMap.getId(), loginUser.getTsysUser().getId(), tablename);
         } else {
            list = this.dataMapService.queryDataMapTable(dataMap.getId(), tablename);
         }

         return list;
      }
   }

   @ResponseBody
   @RequestMapping({"/testtablerelationline"})
   public Map<String, String> testtablerelationline(String datasystemid, String schema, String sourcetablename, String targettableid, HttpServletRequest request, HttpServletResponse response, Model model) {
      TCoreDatamap dataMap = this.dataMapService.queryDataMapUnique(datasystemid, schema);
      if (dataMap == null) {
         return null;
      } else {
         TCoreDatamapTable sourceTable = this.dataMapService.queryDataMapTable(datasystemid, schema, sourcetablename);
         if (sourceTable == null) {
            return null;
         } else {
            TCoreDatamapTablerelation relation = this.dataMapService.queryTableRelation(dataMap.getId(), sourceTable.getId(), targettableid);
            Map<String, String> map = new HashMap();
            if (relation != null) {
               map.put("result", Boolean.TRUE.toString());
            } else {
               map.put("result", Boolean.FALSE.toString());
            }

            return map;
         }
      }
   }

   @ResponseBody
   @RequestMapping({"/savetablerelation"})
   public void savetablerelation(String datasystemid, String schema, String sourcetablename, String targettableid, HttpServletRequest request, HttpServletResponse response, Model model) {
      TCoreDatamap dataMap = this.dataMapService.queryDataMapUnique(datasystemid, schema);
      if (dataMap != null) {
         TCoreDatamapTable sourceTable = this.dataMapService.queryDataMapTable(datasystemid, schema, sourcetablename);
         if (sourceTable != null) {
            this.dataMapService.saveDataMapTableRelation(dataMap.getId(), sourceTable.getId(), targettableid);
         }
      }
   }

   @ResponseBody
   @RequestMapping({"/addusermap"})
   public void addusermap(String datasystemid, String schema, String tablename, HttpServletRequest request, HttpServletResponse response, Model model) {
      TCoreDatamapTable table = this.dataMapService.queryDataMapTable(datasystemid, schema, tablename);
      if (table != null) {
         LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
         if (loginUser != null && loginUser.getTsysUser() != null) {
            TCoreDatamap dataMap = this.dataMapService.queryDataMapUnique(datasystemid, schema);
            if (dataMap != null) {
               this.dataMapService.saveDataMapUserMap(new TCoreDatamapUsermap(table.getId(), loginUser.getTsysUser().getId(), dataMap.getId()));
            }
         }
      }
   }

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

   @ResponseBody
   @RequestMapping({"/removeusermap"})
   public void removeusermap(String datasystemid, String schema, String table, HttpServletRequest request, HttpServletResponse response, Model model) {
      TCoreDatamap dataMap = this.dataMapService.queryDataMapUnique(datasystemid, schema);
      if (dataMap != null) {
         TCoreDatamapTable dataMapTable = this.dataMapService.queryDataMapTable(datasystemid, schema, table);
         if (dataMapTable != null) {
            LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
            if (loginUser != null && loginUser.getTsysUser() != null) {
               this.dataMapService.removeUserMap(dataMap.getId(), dataMapTable.getId(), loginUser.getTsysUser().getId());
            }
         }
      }
   }

   @ResponseBody
   @RequestMapping({"/savenote"})
   public void savenote(@RequestBody SaveNoteParam param, HttpServletRequest request, HttpServletResponse response, Model model) {
      this.dataMapService.saveTableNote(param.getTable());

      for(TCoreDatamapColumn item : param.getColumn()) {
         this.dataMapService.saveColumnNote(item);
      }

   }

   @ResponseBody
   @RequestMapping({"/querytabledata"})
   public Map<String, Object> querytabledata(String tablerelationid, HttpServletRequest request, HttpServletResponse response, Model model) {
      TCoreDatamapTable maptable = this.dataMapService.queryDataMapTableById(tablerelationid);
      TCoreDatamap datamap = this.dataMapService.queryDataMap(maptable.getDatamapid());
      TCoreDatasystem dataSystem = this.dataSystemService.queryDataSystemById(datamap.getDatasystemid());
      String datasystemid = dataSystem.getId();
      String schemaname = datamap.getDbschema();
      String tablename = maptable.getTablename();
      Connection conn = this.dataSystemService.getConnectionByDataSystemId(datasystemid);
      List<String> columnnamelist = JdbcTool.getAllColumnNameList(conn, schemaname, tablename);

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

      StringBuffer sql = new StringBuffer();
      sql.append(" select ");

      for(int i = 0; i < columnnamelist.size(); ++i) {
         sql.append((String)columnnamelist.get(i) + " ");
         if (i < columnnamelist.size() - 1) {
            sql.append(",");
         }
      }

      sql.append(" from ");
      sql.append(schemaname + "." + tablename);
      conn = this.dataSystemService.getConnectionByDataSystemId(datasystemid);
      Statement st = null;
      ResultSet rs = null;
      StringBuffer jsonStr = null;

      try {
         String sql_select = JdbcTool.getQueryStringByConnection(conn, sql.toString(), 0, 10);
         st = conn.createStatement();
         rs = st.executeQuery(sql_select);
         int i = 0;

         while(rs.next()) {
            ++i;
            if (i > 10) {
               break;
            }

            if (jsonStr == null) {
               jsonStr = new StringBuffer();
            } else {
               jsonStr.append(",");
            }

            jsonStr.append("{");

            for(int j = 0; j < columnnamelist.size(); ++j) {
               jsonStr.append("\"" + (String)columnnamelist.get(j) + "\":\"" + rs.getString((String)columnnamelist.get(j)) + "\"");
               if (j < columnnamelist.size() - 1) {
                  jsonStr.append(",");
               }
            }

            jsonStr.append("}");
         }
      } catch (SQLException e) {
         e.printStackTrace();
      } finally {
         try {
            if (rs != null) {
               rs.close();
            }

            if (st != null) {
               st.close();
            }

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

      }

      if (jsonStr == null) {
         jsonStr = new StringBuffer();
      }

      Map<String, Object> vo = new HashMap();
      vo.put("message", "[" + jsonStr.toString() + "]");
      return vo;
   }

   @ResponseBody
   @RequestMapping({"/testtasknameexist"})
   public Map<String, String> testtasknameexist(String engineid, String taskname, HttpServletRequest request, HttpServletResponse response, Model model) {
      TCoreMaskingTask task = this.dataMapService.queryMaskingTask(engineid, taskname);
      Map<String, String> map = new HashMap();
      if (task != null) {
         map.put("result", Boolean.TRUE.toString());
      } else {
         map.put("result", Boolean.FALSE.toString());
      }

      return map;
   }

   @ResponseBody
   @RequestMapping({"/querydatasystembytablerelationid"})
   public Map<String, String> querydatasystembytablerelationid(String tableid, HttpServletRequest request, HttpServletResponse response, Model model) {
      TCoreDatamapTable table = this.dataMapService.queryDataMapTableById(tableid);
      TCoreDatamap datamap = this.dataMapService.queryDataMap(table.getDatamapid());
      TCoreDatasystem datasystem = this.dataSystemService.queryDataSystemById(datamap.getDatasystemid());
      Map<String, String> map = new HashMap();
      map.put("datasystemid", datasystem.getId());
      map.put("datasystemname", datasystem.getSysname());
      map.put("datasystemschema", datamap.getDbschema());
      return map;
   }

   @ResponseBody
   @RequestMapping({"/savetask"})
   public TCoreMaskingTask savetask(String engineid, String folderName, String taskname, String note, String tableid, String datatargetid, String datatargetschema, String targetTableName, HttpServletRequest request, HttpServletResponse response, Model model) {
      LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
      String userid = loginUser.getTsysUser().getId();
      TCoreMaskingTask task = this.dataMapService.saveTask(userid, engineid, folderName, taskname, note, tableid, datatargetid, datatargetschema, targetTableName);
      return task;
   }
}
