package com.chenyang.nse.bussiness.service.core.impl;

import com.chenyang.nse.bussiness.dao.PageInfo;
import com.chenyang.nse.bussiness.dao.table.core.TCoreDatasystemDao;
import com.chenyang.nse.bussiness.dao.table.core.api.ApiHeaderParameterDao;
import com.chenyang.nse.bussiness.dao.table.core.api.ApiInfoDao;
import com.chenyang.nse.bussiness.dao.table.core.api.ApiSysParameterDao;
import com.chenyang.nse.bussiness.dao.table.core.dataproject.TCoreDiscoverytaskDao;
import com.chenyang.nse.bussiness.dao.table.core.dataproject.TCoreProjectDatasourceDao;
import com.chenyang.nse.bussiness.dao.table.core.dataproject.TCoreProjectFileDao;
import com.chenyang.nse.bussiness.dao.table.core.dataproject.TCoreProjectFindruleDao;
import com.chenyang.nse.bussiness.dao.table.core.dataproject.TCoreProjectVersionDao;
import com.chenyang.nse.bussiness.dao.table.core.dataproject.TCoreTaskFindruleDao;
import com.chenyang.nse.bussiness.dao.table.core.dataproject.TcoreDiscoveryColumnDao;
import com.chenyang.nse.bussiness.dao.table.core.dataproject.TcoreDiscoveryDataResultDao;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystem;
import com.chenyang.nse.bussiness.entity.orm.table.core.api.ApiHeaderParameter;
import com.chenyang.nse.bussiness.entity.orm.table.core.api.ApiInfo;
import com.chenyang.nse.bussiness.entity.orm.table.core.api.ApiSysParameter;
import com.chenyang.nse.bussiness.entity.orm.table.core.dataproject.TCoreProjectFile;
import com.chenyang.nse.bussiness.entity.orm.table.core.dataproject.TCoreProjectVersion;
import com.chenyang.nse.bussiness.entity.orm.table.core.discovery.TcoreDiscoveryColumn;
import com.chenyang.nse.bussiness.entity.orm.table.core.discovery.TcoreDiscoveryDataResult;
import com.chenyang.nse.bussiness.entity.orm.table.core.discovery.TcoreDiscoveryTask;
import com.chenyang.nse.bussiness.entity.orm.table.core.discovery.TcoreTaskFindrule;
import com.chenyang.nse.bussiness.entity.vo.ComboboxVO;
import com.chenyang.nse.bussiness.entity.vo.ResultVO;
import com.chenyang.nse.bussiness.entity.vo.api.ApiInfoObjectVO;
import com.chenyang.nse.bussiness.service.core.TdataDiscoveryService;
import com.chenyang.nse.bussiness.tools.io.FileTool;
import com.chenyang.nse.bussiness.tools.net.FtpTool;
import com.chenyang.nse.bussiness.tools.net.SFTPUtil;
import com.jcraft.jsch.SftpException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.Vector;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class TdataDiscoveryServiceImpl implements TdataDiscoveryService {
   @Autowired
   private TCoreTaskFindruleDao tCoreTaskFindruleDao;
   @Autowired
   private TCoreDiscoverytaskDao tCoreDiscoverytaskDao;
   @Autowired
   private TcoreDiscoveryColumnDao tcoreDiscoveryColumnDao;
   @Autowired
   private TCoreDatasystemDao tCoreDatasystemDao;
   @Autowired
   private TCoreProjectVersionDao tCoreDiscoveryVersrionDao;
   @Autowired
   private TCoreProjectFindruleDao tCoreProjectFindruleDao;
   @Autowired
   private TcoreDiscoveryDataResultDao tcoreDiscoveryDataResultDao;
   @Autowired
   private TCoreProjectFileDao tCoreProjectFileDao;
   @Autowired
   private TCoreProjectDatasourceDao tCoreProjectDatasourceDao;
   @Autowired
   private ApiInfoDao apiInfoDao;
   @Autowired
   private ApiSysParameterDao apiSysParameterDao;
   @Autowired
   private ApiHeaderParameterDao apiHeaderParameterDao;

   public TcoreDiscoveryTask queryTaskByName(String taskname, String datasystemid) {
      List<TcoreDiscoveryTask> discoverytasklist = this.tCoreDiscoverytaskDao.queryAll(Order.desc("createtime"), new Criterion[]{Restrictions.eq("tname", taskname), Restrictions.eq("datasystemid", datasystemid)});
      return discoverytasklist != null && discoverytasklist.size() > 0 ? (TcoreDiscoveryTask)discoverytasklist.get(0) : null;
   }

   public TcoreDiscoveryTask queryTaskByid(String taskid) {
      TcoreDiscoveryTask tcoreDiscoveryTask = (TcoreDiscoveryTask)this.tCoreDiscoverytaskDao.queryUnique(new Criterion[]{Restrictions.eq("id", taskid)});
      return tcoreDiscoveryTask;
   }

   public List<TCoreProjectFile> queryTaskBytaskid(String taskid) {
      List<TCoreProjectFile> tCoreProjectFile = this.tCoreProjectFileDao.queryAll(new Criterion[]{Restrictions.eq("taskid", taskid)});
      return tCoreProjectFile;
   }

   public void saveDiscoveryTask(Map<String, Object> map, Date nowdate, String resultid, String projectid) {
      TcoreDiscoveryTask tcoreDiscoveryTask = new TcoreDiscoveryTask();
      String taskid = map.get("taskid").toString();
      tcoreDiscoveryTask.setUpdatetime(nowdate);
      tcoreDiscoveryTask.setTname(map.get("taskname").toString());
      tcoreDiscoveryTask.setNote(map.get("remark").toString());
      tcoreDiscoveryTask.setDiscoverytype(map.get("discoverytype").toString());
      tcoreDiscoveryTask.setCyfs(map.get("cyfs").toString());
      tcoreDiscoveryTask.setCys(map.get("cys").toString());
      tcoreDiscoveryTask.setPpl(map.get("ppl").toString());
      tcoreDiscoveryTask.setUsername(map.get("username").toString());
      tcoreDiscoveryTask.setId(map.get("taskid").toString());
      tcoreDiscoveryTask.setFlag(map.get("flag").toString());
      tcoreDiscoveryTask.setDatasystemid(map.get("datasystemid").toString());
      tcoreDiscoveryTask.setProjectid(projectid);
      tcoreDiscoveryTask.setAlltableschema(String.valueOf(map.get("alltableschema")));
      if (!"2".equals(map.get("discoverytype").toString())) {
         String datasourceid = map.get("datasystemid").toString();
         String dbtype = ((TCoreDatasystem)this.tCoreDatasystemDao.queryUnique(new Criterion[]{Restrictions.eq("id", datasourceid)})).getDbtype();
         tcoreDiscoveryTask.setDbtype(dbtype);
      } else {
         tcoreDiscoveryTask.setDbtype(map.get("filesourcetype").toString());
         if ("0".equals(map.get("filetype").toString())) {
            tcoreDiscoveryTask.setIsdmpflag("1");
         }
      }

      String taskedit = map.get("taskedit").toString();
      if (taskedit != null && !"".equals(taskedit)) {
         tcoreDiscoveryTask.setUpdatetime(nowdate);
         this.tCoreDiscoverytaskDao.editDiscoveryTask(tcoreDiscoveryTask);
      } else {
         tcoreDiscoveryTask.setCreatetime(nowdate);
         tcoreDiscoveryTask.setUpdatetime(nowdate);
         tcoreDiscoveryTask.setResultid("R_" + resultid);
         this.tCoreDiscoverytaskDao.createDiscoveryTask(tcoreDiscoveryTask);
      }

      List<String> ruleidlist = (List)map.get("ruleidlist");
      this.tCoreTaskFindruleDao.remove(new Criterion[]{Restrictions.eq("taskid", taskid)});
      if (ruleidlist.size() > 0) {
         for(int i = 0; i < ruleidlist.size(); ++i) {
            TcoreTaskFindrule tcoreTaskFindrule = new TcoreTaskFindrule();
            tcoreTaskFindrule.setId(UUID.randomUUID().toString());
            tcoreTaskFindrule.setProjectid(projectid);
            tcoreTaskFindrule.setTaskid(taskid);
            tcoreTaskFindrule.setDataareaid(((String)ruleidlist.get(i)).split("#\\|#")[0]);
            tcoreTaskFindrule.setDataarea(((String)ruleidlist.get(i)).split("#\\|#")[1]);
            tcoreTaskFindrule.setFlag(((String)ruleidlist.get(i)).split("#\\|#")[4]);
            tcoreTaskFindrule.setRulename(((String)ruleidlist.get(i)).split("#\\|#")[7]);
            tcoreTaskFindrule.setDiscoverway(((String)ruleidlist.get(i)).split("#\\|#")[5]);
            tcoreTaskFindrule.setRegex(((String)ruleidlist.get(i)).split("#\\|#")[3]);
            tcoreTaskFindrule.setRuleid(((String)ruleidlist.get(i)).split("#\\|#")[2]);
            this.tCoreTaskFindruleDao.save(tcoreTaskFindrule);
         }
      }

   }

   public List<TcoreDiscoveryTask> queryDiscoverytasklist(PageInfo pageInfo, String projectid) {
      List<TcoreDiscoveryTask> list = this.tCoreDiscoverytaskDao.queryByPageInfo(pageInfo, Order.desc("updatetime"), new Criterion[]{Restrictions.eq("projectid", projectid)});
      return list;
   }

   public List<TcoreDiscoveryTask> queryDiscoverytasklistByProjectId(String projectid) {
      List<TcoreDiscoveryTask> list = this.tCoreDiscoverytaskDao.queryAll(Order.desc("updatetime"), new Criterion[]{Restrictions.eq("projectid", projectid)});
      return list;
   }

   public void delDiscoveryColumn(String taskid) {
      this.tcoreDiscoveryColumnDao.deleteDiscoveryColumn(taskid);
   }

   public List<TcoreDiscoveryColumn> queryDiscoveryColumn(String taskid) {
      List<TcoreDiscoveryColumn> discoveryColumnlist = this.tcoreDiscoveryColumnDao.queryAll(Order.desc("tschema"), new Criterion[]{Restrictions.eq("taskid", taskid)});
      return discoveryColumnlist;
   }

   public List<TCoreProjectFile> queryDiscoveryFile(String taskid) {
      List<TCoreProjectFile> discoveryfilelist = this.tCoreProjectFileDao.queryAll(new Criterion[]{Restrictions.eq("taskid", taskid)});
      return discoveryfilelist;
   }

   public void queryCountRes(List<TcoreDiscoveryTask> tcoreDiscoveryTaskList) {
      for(TcoreDiscoveryTask task : tcoreDiscoveryTaskList) {
         StringBuilder sb = new StringBuilder();
         List<Map<String, Object>> issSureFieldcountList = this.tCoreDiscoverytaskDao.selectIsSureFieldcount(task.getResultid());
         if (issSureFieldcountList.size() > 0) {
            sb.append(((Map)issSureFieldcountList.get(0)).get("count"));
         } else {
            sb.append(0);
         }

         sb.append("/");
         List<Map<String, Object>> fieldcountList = this.tCoreDiscoverytaskDao.selectFieldcount(task.getId());
         if (fieldcountList.size() > 0) {
            sb.append(((Map)fieldcountList.get(0)).get("count"));
         } else {
            sb.append(0);
         }

         task.setCountResult(sb.toString());
      }

   }

   public List<TcoreTaskFindrule> queryFindrulelist(String taskid) {
      List<TcoreTaskFindrule> findruleList = this.tCoreTaskFindruleDao.queryAll(new Criterion[]{Restrictions.eq("taskid", taskid)});
      return findruleList;
   }

   public long getExeTaskNum(String taskid) {
      return this.tCoreDiscoverytaskDao.getExeTaskNum(taskid);
   }

   public void updateTaskstatus(String taskid, String status, String version) {
      if ("all_version".equals(version)) {
         version = "3";
      } else if ("project_version".equals(version)) {
         version = "2";
      } else if (StringUtils.isNotBlank(version) || !"0".equals(version)) {
         version = "1";
      }

      this.tCoreDiscoverytaskDao.updateTaskstatus(taskid, status, version);
   }

   public void updateAutofindResultid(String taskid, String resultid) {
      TcoreDiscoveryTask tcoreDiscoveryTask = (TcoreDiscoveryTask)this.tCoreDiscoverytaskDao.get(taskid);
      tcoreDiscoveryTask.setAutofindresultid(resultid);
      this.tCoreDiscoverytaskDao.update(tcoreDiscoveryTask);
   }

   public List<TCoreProjectVersion> initExcute(String taskid, String projectid) {
      return this.tCoreDiscoveryVersrionDao.queryAllPro(taskid, projectid);
   }

   public void createsqlstr(StringBuilder sql) {
      this.tCoreDiscoverytaskDao.createsqlstr(sql);
   }

   public void saveDiscoveryDataResult(TcoreDiscoveryDataResult tcoreDiscoveryDataResult) {
      this.tcoreDiscoveryDataResultDao.save(tcoreDiscoveryDataResult);
   }

   public void delDiscoveryDataResult(String taskid) {
      this.tcoreDiscoveryDataResultDao.remove(new Criterion[]{Restrictions.eq("taskid", taskid)});
   }

   public void saveTCoreProjectFile(TCoreProjectFile tCoreProjectFile) {
      this.tCoreProjectFileDao.save(tCoreProjectFile);
   }

   public void deleteTCoreProjectFile(String taskid) {
      this.tCoreProjectFileDao.remove(new Criterion[]{Restrictions.eq("taskid", taskid)});
   }

   public List<String> querydir(String path) {
      return FileTool.getPathFile(path);
   }

   public Map<String, Object> queryFtpdir(String url, int port, String username, String password, String path, String substring, String code) {
      Map<String, Object> map = new HashMap();
      new HashMap();
      new ArrayList();

      try {
         Map<String, Object> filemap = FtpTool.listFiles(url, port, username, password, path, substring, code);
         if ((Boolean)filemap.get("fileresult")) {
            List<Map<String, String>> list = (List)filemap.get("filelist");
            map.put("list", list);
            map.put("listresult", true);
         } else {
            map.put("listresult", false);
            map.put("message", filemap.get("filelist"));
         }
      } catch (Exception e) {
         e.printStackTrace();
         map.put("listresult", false);
         map.put("message", getExceptionSrintStackTrace(e));
      }

      return map;
   }

   public Map<String, Object> querySftpdir(String url, int port, String ip, String username, String password) {
      Map<String, Object> map = new HashMap();
      Vector<?> list = new Vector();
      SFTPUtil sftp = new SFTPUtil(username, password, ip, port);
      ResultVO resultVo = SFTPUtil.login();
      if (resultVo.getResult()) {
         try {
            list = sftp.listFiles(url);
            map.put("listresult", true);
         } catch (SftpException e) {
            e.printStackTrace();
            map.put("listresult", false);
            map.put("message", "文件路径输入错误");
         }
      } else {
         map.put("listresult", false);
         map.put("message", resultVo.getMessage());
      }

      map.put("list", list);
      sftp.logout();
      return map;
   }

   public static String getExceptionSrintStackTrace(Exception e) {
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      e.printStackTrace(pw);
      return sw.toString();
   }

   public List<ComboboxVO> queryfilesource(String projectid, String filetype, String userid) {
      return this.tCoreProjectDatasourceDao.queryFilesource(projectid, filetype, userid);
   }

   public List<TCoreProjectFile> queryFilelist(String taskid) {
      return this.tCoreProjectFileDao.queryAll(new Criterion[]{Restrictions.eq("taskid", taskid)});
   }

   public String saveApiInfo(ApiInfoObjectVO apiInfoObjectVo) {
      ApiInfo apiInfo = apiInfoObjectVo.getApiInfo();
      List<ApiHeaderParameter> apiHeaderParameterList = apiInfoObjectVo.getApiHeaderParameterList();
      List<ApiSysParameter> apiSysParameterList = apiInfoObjectVo.getApiSysParameterList();
      if (apiInfo.getId() != null && !"".equals(apiInfo.getId())) {
         this.apiInfoDao.saveOrUpdate(apiInfo);
         String apiInfoid = apiInfo.getId();
         this.apiHeaderParameterDao.remove(new Criterion[]{Restrictions.eq("apiInfoId", apiInfoid)});
         this.apiSysParameterDao.remove(new Criterion[]{Restrictions.eq("apiInfoId", apiInfoid)});

         for(ApiHeaderParameter apiHeaderParameter : apiHeaderParameterList) {
            apiHeaderParameter.setApiInfoId(apiInfoid);
            apiHeaderParameter.setId((String)null);
            this.apiHeaderParameterDao.saveOrUpdate(apiHeaderParameter);
         }

         for(ApiSysParameter apiSysParameter : apiSysParameterList) {
            apiSysParameter.setApiInfoId(apiInfoid);
            apiSysParameter.setId((String)null);
            this.apiSysParameterDao.saveOrUpdate(apiSysParameter);
         }
      } else {
         this.apiInfoDao.save(apiInfo);

         for(ApiHeaderParameter apiHeaderParameter : apiHeaderParameterList) {
            apiHeaderParameter.setApiInfoId(apiInfo.getId());
            this.apiHeaderParameterDao.save(apiHeaderParameter);
         }

         for(ApiSysParameter apiSysParameter : apiSysParameterList) {
            apiSysParameter.setApiInfoId(apiInfo.getId());
            this.apiSysParameterDao.save(apiSysParameter);
         }
      }

      return "1";
   }

   public ApiInfoObjectVO selectApiInfo(String taskid) {
      ApiInfoObjectVO apiInfoObjectVO = new ApiInfoObjectVO();
      List<ApiInfo> list = this.apiInfoDao.queryAll(new Criterion[]{Restrictions.eq("taskId", taskid)});
      if (list.size() <= 0) {
         return apiInfoObjectVO;
      } else {
         for(ApiInfo apiInfo : list) {
            apiInfoObjectVO.setApiInfo(apiInfo);
            String id = apiInfo.getId();
            List<ApiHeaderParameter> apiHeaderParameterList = this.apiHeaderParameterDao.queryAll(new Criterion[]{Restrictions.eq("apiInfoId", id)});
            apiInfoObjectVO.setApiHeaderParameterList(apiHeaderParameterList);
            List<ApiSysParameter> apiSysParameterList = this.apiSysParameterDao.queryAll(new Criterion[]{Restrictions.eq("apiInfoId", id)});
            apiInfoObjectVO.setApiSysParameterList(apiSysParameterList);
         }

         return apiInfoObjectVO;
      }
   }

   public int releaseByTreeId(String treeid) {
      int count = this.apiInfoDao.releaseByTreeId(treeid);
      return count;
   }

   public int releaseAll() {
      int count = this.apiInfoDao.releaseAll();
      return count;
   }

   public boolean isRepeatName(String projectid, String taskname, String taskid) {
      new ArrayList();
      List discoveryTaskList;
      if (!taskid.equals("") && taskid != null) {
         discoveryTaskList = this.tCoreDiscoverytaskDao.queryAll(new Criterion[]{Restrictions.eq("tname", taskname), Restrictions.eq("projectid", projectid), Restrictions.ne("id", taskid)});
      } else {
         discoveryTaskList = this.tCoreDiscoverytaskDao.queryAll(new Criterion[]{Restrictions.eq("tname", taskname), Restrictions.eq("projectid", projectid)});
      }

      return discoveryTaskList.size() == 0;
   }
}
