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

import com.chenyang.nse.bussiness.commmon.json.RespHelper;
import com.chenyang.nse.bussiness.commmon.json.Response;
import com.chenyang.nse.bussiness.dao.PageInfo;
import com.chenyang.nse.bussiness.dao.table.core.TCoreDatasystemDao;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDataPreviewSQL;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystem;
import com.chenyang.nse.bussiness.entity.vo.DataPreviewVO;
import com.chenyang.nse.bussiness.service.core.DataPreviewService;
import com.chenyang.nse.bussiness.tools.jdbc.MongodbTool;
import com.chenyang.nse.bussiness.tools.string.AesTool;
import com.chenyang.nse.bussiness.tools.string.StringTool;
import com.mongodb.MongoClient;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@EnableAsync
@Controller
@RequestMapping({"/core/datapreview"})
public class DataPreviewController {
   private static Logger logger = LoggerFactory.getLogger(DataPreviewController.class);
   @Autowired
   private DataPreviewService dataPreviewService;
   @Autowired
   private TCoreDatasystemDao tCoreDatasystemDao;

   @ResponseBody
   @PostMapping({"/query"})
   public Response<DataPreviewVO> queryPreviewBysql(@RequestBody DataPreviewVO dataPreviewVO) {
      PageInfo pageInfo = new PageInfo();
      pageInfo.setPageno(dataPreviewVO.getPage());
      pageInfo.setPagesize(dataPreviewVO.getRows());
      TCoreDatasystem tCoreDatasystem = (TCoreDatasystem)this.tCoreDatasystemDao.get(dataPreviewVO.getDatasystem_id());
      if ("ES".equals(tCoreDatasystem.getDbtype())) {
         long s = System.currentTimeMillis();
         DataPreviewVO retDataPreviewVO = new DataPreviewVO();
         String es = this.dataPreviewService.esQueryDataPreview(tCoreDatasystem, dataPreviewVO.getSql());
         long e = System.currentTimeMillis();
         retDataPreviewVO.setExecute_time(e - s);
         TCoreDataPreviewSQL tcoreDataPreviewSQL = new TCoreDataPreviewSQL();
         tcoreDataPreviewSQL.setExesql(dataPreviewVO.getSql());
         tcoreDataPreviewSQL.setSchem(dataPreviewVO.getSchema());
         tcoreDataPreviewSQL.setDatasystem_id(dataPreviewVO.getDatasystem_id());
         tcoreDataPreviewSQL.setId(StringTool.getTablePrimaryKey());
         tcoreDataPreviewSQL.setCreatetime(new Date());
         String[] sqls = dataPreviewVO.getSql().split("/");
         String table_name = sqls[2];
         tcoreDataPreviewSQL.setTablename(table_name);
         List<String> strings = new ArrayList();
         strings.add(es);
         retDataPreviewVO.setEsdata(strings);
         return RespHelper.<DataPreviewVO>successResp(retDataPreviewVO);
      } else if ("MONGODB".equals(tCoreDatasystem.getDbtype())) {
         long s = System.currentTimeMillis();
         DataPreviewVO retDataPreviewVO = new DataPreviewVO();
         long e = System.currentTimeMillis();
         retDataPreviewVO.setExecute_time(e - s);
         String[] sqls = dataPreviewVO.getSql().split("\\.");
         String table_name = sqls[1];

         try {
            MongoClient client = MongodbTool.connect(tCoreDatasystem.getDbservername(), tCoreDatasystem.getUsername(), AesTool.decrypt(tCoreDatasystem.getPassword(), "ghca"), tCoreDatasystem.getDbip(), Integer.parseInt(tCoreDatasystem.getDbport()), true);
            List<String> strings = MongodbTool.findAllDataPreview(client, dataPreviewVO.getSchema(), table_name);
            TCoreDataPreviewSQL tcoreDataPreviewSQL = new TCoreDataPreviewSQL();
            tcoreDataPreviewSQL.setExesql(dataPreviewVO.getSql());
            tcoreDataPreviewSQL.setSchem(dataPreviewVO.getSchema());
            tcoreDataPreviewSQL.setDatasystem_id(dataPreviewVO.getDatasystem_id());
            tcoreDataPreviewSQL.setId(StringTool.getTablePrimaryKey());
            tcoreDataPreviewSQL.setCreatetime(new Date());
            tcoreDataPreviewSQL.setTablename(table_name);
            String ss = "";

            for(int i = 0; i < strings.size(); ++i) {
               if (i != 0) {
                  ss = ss + "," + (String)strings.get(i);
               } else {
                  ss = ss + (String)strings.get(i);
               }
            }

            retDataPreviewVO.setEsdata(strings);
         } catch (Exception exception) {
            exception.printStackTrace();
         }

         return RespHelper.<DataPreviewVO>successResp(retDataPreviewVO);
      } else {
         long s = System.currentTimeMillis();
         String sql = dataPreviewVO.getSql();
         if (!sql.trim().toLowerCase().startsWith("select")) {
            return RespHelper.<DataPreviewVO>errRespStr("只支持查询功能语句！");
         } else {
            DataPreviewVO retDataPreviewVO = this.dataPreviewService.queryDataPreviewBysql(pageInfo, dataPreviewVO);
            long e = System.currentTimeMillis();
            retDataPreviewVO.setExecute_time(e - s);
            retDataPreviewVO.setPageInfo(pageInfo);
            return RespHelper.<DataPreviewVO>successResp(retDataPreviewVO);
         }
      }
   }

   @ResponseBody
   @PostMapping({"/querySqlHistory"})
   public Response<List<TCoreDataPreviewSQL>> querySqlHistory(@RequestBody TCoreDataPreviewSQL coreDataPreviewSQL) {
      String datasystem_id = "";
      if (!StringUtils.isBlank(coreDataPreviewSQL.getDatasystem_id())) {
         datasystem_id = coreDataPreviewSQL.getDatasystem_id();
      }

      List<TCoreDataPreviewSQL> hisList = this.dataPreviewService.queryDataPreviewHis(datasystem_id);
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      hisList.stream().limit(10L).forEach((hist) -> hist.setCreatetimeOfstr(sdf.format(hist.getCreatetime())));
      return RespHelper.<List<TCoreDataPreviewSQL>>successResp(hisList);
   }
}
