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.core.TCoreDatasystem;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreEngine;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreSubset;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreSubsetcolumns;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreSubsettask;
import com.chenyang.nse.bussiness.entity.vo.ComboboxVO;
import com.chenyang.nse.bussiness.entity.vo.DataGridVO;
import com.chenyang.nse.bussiness.entity.vo.ResultVO;
import com.chenyang.nse.bussiness.entity.vo.SubsetTaskEngineVO;
import com.chenyang.nse.bussiness.service.core.DataSystemService;
import com.chenyang.nse.bussiness.service.core.ImportMaskingRuleService;
import com.chenyang.nse.bussiness.service.core.SubsetService;
import com.chenyang.nse.bussiness.tools.jdbc.JdbcTool;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
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/subdatataskmanager"})
public class SubsetDataTaskManagerController {
   private static Logger logger = LoggerFactory.getLogger(SubsetDataTaskManagerController.class);
   @Autowired
   private SubsetService subsetService;
   @Autowired
   private ImportMaskingRuleService importMaskingRuleService;
   @Autowired
   private DataSystemService dataSystemService;

   @RequestMapping
   public String index(HttpServletRequest request, HttpServletResponse response, Model model) {
      LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
      model.addAttribute("privileges", loginUser.getPrivileges());
      return "core/subsetdatataskmanager/subdatataskmanager";
   }

   @ResponseBody
   @RequestMapping({"/queryAllSubset"})
   public List<TCoreSubset> queryAllSubset(HttpServletRequest request, HttpServletResponse response, Model model) {
      return this.subsetService.queryAllSubset();
   }

   @ResponseBody
   @RequestMapping({"/delete"})
   public boolean delete(String id, HttpServletRequest request, HttpServletResponse response, Model model) {
      this.subsetService.delete(id);
      return true;
   }

   @ResponseBody
   @RequestMapping({"/modify"})
   public boolean modify(TCoreSubset subset, HttpServletRequest request, HttpServletResponse response, Model model) {
      if ("0".equals(subset.getState())) {
         request.getSession().setAttribute("lastDefinedSubsetName", subset.getTname());
      } else {
         request.getSession().setAttribute("lastSelectSubsetName", subset.getTname());
      }

      return true;
   }

   @ResponseBody
   @RequestMapping({"/checkTaskName"})
   public boolean checkTaskName(String taskName, HttpServletRequest request, HttpServletResponse response, Model model) {
      return this.subsetService.checkTaskName(taskName);
   }

   @ResponseBody
   @RequestMapping({"/querySubsetColumns"})
   public List<TCoreSubsetcolumns> querySubsetColumns(String subsetid, HttpServletRequest request, HttpServletResponse response, Model model) {
      List<TCoreSubsetcolumns> list = this.subsetService.querySubsetColumns(subsetid);
      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({"/querytask"})
   public DataGridVO<TCoreSubsettask> querytask(Integer page, Integer rows, PageInfo pageInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
      pageInfo.setPageno(page);
      pageInfo.setPagesize(rows);
      List<TCoreSubsettask> list = this.subsetService.queryTask(pageInfo);
      DataGridVO<TCoreSubsettask> result = new DataGridVO<TCoreSubsettask>(pageInfo.getCount(), list);
      return result;
   }

   @ResponseBody
   @RequestMapping({"/saveSubsetTask"})
   public TCoreSubsettask saveSubsetTask(TCoreSubsettask subsetTask, HttpServletRequest request, HttpServletResponse response, Model model) {
      LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
      return this.subsetService.queryTaskById(this.subsetService.saveSubsetTask(subsetTask, loginUser.getTsysUser().getId()));
   }

   @RequestMapping({"/deleteSubsetTask"})
   public void deleteSubsetTask(String subsetTaskId, HttpServletRequest request, HttpServletResponse response, Model model) {
      this.subsetService.deleteSubsetTask(subsetTaskId);
   }

   @ResponseBody
   @RequestMapping({"/executeTask"})
   public String executeTask(TCoreSubsettask subsetTask, HttpServletRequest request, HttpServletResponse response, Model model) {
      return this.subsetService.executeTask(subsetTask);
   }

   @ResponseBody
   @RequestMapping({"/getEngineInfoOfSubsetTask"})
   public SubsetTaskEngineVO getEngineInfoOfSubsetTask(String subsetTaskId, HttpServletRequest request, HttpServletResponse response, Model model) {
      return this.subsetService.getEngineInfoOfSubsetTask(subsetTaskId);
   }

   @ResponseBody
   @RequestMapping({"/querydatasystem"})
   public List<TCoreDatasystem> querydatasource(HttpServletRequest request, HttpServletResponse response, Model model) {
      return this.dataSystemService.querydatasource();
   }

   @ResponseBody
   @RequestMapping({"/queryShemas"})
   public List<ComboboxVO> queryShemas(String dbType, String dataSystemId, HttpServletRequest request, HttpServletResponse response, Model model) {
      return this.dataSystemService.queryShemas(dbType, dataSystemId);
   }

   @ResponseBody
   @RequestMapping({"/checkWhereStatement"})
   public ResultVO checkWhereStatement(String dataSystemId, String schema, String whereStatements, HttpServletRequest request, HttpServletResponse response, Model model) {
      TCoreDatasystem datasystem = this.dataSystemService.queryDataSystemById(dataSystemId);
      this.iskeberos(datasystem);
      Connection conn = JdbcTool.getConnection(datasystem);
      String[] arr = whereStatements.split(",");

      for(String tableWhere : arr) {
         String[] tempArr = tableWhere.split(":");
         if (tempArr.length != 2) {
            return new ResultVO("过滤条件格式不正确！", false);
         }

         String sql = MessageFormat.format("select * from {0}.{1} where {2}", schema, tempArr[0], tempArr[1]);

         try {
            PreparedStatement statement = conn.prepareStatement(sql);
            ResultSet resultSet = statement.executeQuery();
            resultSet.close();
            statement.close();
         } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
            return new ResultVO(tempArr[0] + ": " + e.getMessage(), false);
         }
      }

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

      return new ResultVO((String)null, true);
   }

   @RequestMapping({"/setModifiedSubsetTaskId"})
   public void setModifiedSubsetTaskId(String id, HttpServletRequest request, HttpServletResponse response, Model model) {
      request.getSession().setAttribute("modifiedSubsetTaskId", id);
   }

   @RequestMapping({"/monitor"})
   public String monitor(String taskid, String recordid, HttpServletRequest request, HttpServletResponse response, Model model) {
      model.addAttribute("taskid", taskid);
      model.addAttribute("recordid", recordid);
      return "core/maskingtask/monitor";
   }

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

   }
}
