package com.chenyang.nse.bussiness.tools.jdbc;

import com.chenyang.nse.bussiness.config.PropertiesLoaderUtils;
import com.chenyang.nse.bussiness.tools.command.CommandTool;
import com.chenyang.nse.bussiness.tools.datatime.DateTimeTool;
import com.chenyang.nse.bussiness.tools.io.FileTool;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang.StringUtils;

public class TeradataTool {
   public static String STR_SCRIPTFILE_PATH = "/data/infa_work_report/teradata_script/";
   public static String STR_PIPEFILE_PATH = "/data/infa_work_report/tempfile/teradata/";
   public static String STR_PIPEFILE_TAR_PATH = "/data/infa_work_report/tempfile/teradata_target/";
   public static String STR_COL_SPLIT_PATH = "|";
   public static String STR_FASTEXP_CHARACTER = "utf8";

   public static void createTerdataExportScript(Map<String, String> paramMap) {
      String curStartTime = DateTimeTool.getSysTime("");
      System.out.println("++++++++++++++++++++>>>>>>>>>>>>>>start createTerdataExportScript+++++++++++++++++++++++++++++ " + curStartTime);
      String taskname = (String)paramMap.get("taskname");
      String teradataServersIp = (String)paramMap.get("teradataServersIp");
      String teradataServersUser = (String)paramMap.get("teradataServersUser");
      String teradataServerspwd = (String)paramMap.get("teradataServerspwd");
      String schema = (String)paramMap.get("schema");
      String tablename = (String)paramMap.get("tablename");
      String colNamesStr = (String)paramMap.get("colNamesStr");
      String pipeFilePath = STR_PIPEFILE_PATH + taskname + "/";
      String pipeFileTarPath = STR_PIPEFILE_TAR_PATH + taskname + "/";
      File sPath = new File(pipeFilePath);
      if (!sPath.exists()) {
         sPath.mkdirs();
      }

      File tarPath = new File(pipeFileTarPath);
      if (!tarPath.exists()) {
         tarPath.mkdirs();
      }

      String pipeFileName = tablename + ".pipe";
      String scriptFilePath = STR_SCRIPTFILE_PATH + taskname + "/";
      String scriptFileName = tablename + ".fx";
      File scriptFile = new File(scriptFilePath + scriptFileName);
      if (scriptFile.isFile() && scriptFile.exists()) {
         scriptFile.delete();
      }

      StringBuffer scptStr = new StringBuffer();
      scptStr.append(".LOGTABLE " + schema + "." + tablename + "_log;" + System.getProperty("line.separator"));
      scptStr.append(".LOGON " + teradataServersIp + "/" + teradataServersUser + "," + teradataServerspwd + ";" + System.getProperty("line.separator"));
      scptStr.append("DATABASE " + schema + ";" + System.getProperty("line.separator"));
      scptStr.append(".BEGIN EXPORT SESSIONS 4;" + System.getProperty("line.separator"));
      scptStr.append(".EXPORT OUTFILE " + pipeFilePath + pipeFileName + " MODE RECORD FORMAT TEXT;" + System.getProperty("line.separator"));
      scptStr.append("SELECT " + colNamesStr + "as export_cols FROM " + schema + "." + tablename + ";" + System.getProperty("line.separator"));
      scptStr.append(".END EXPORT;" + System.getProperty("line.separator"));
      scptStr.append(".LOGOFF;" + System.getProperty("line.separator"));
      System.out.println(">>>>>>>>>>>>>>script content:" + scptStr.toString());
      FileTool.writeContentToFile(scriptFilePath + scriptFileName, scptStr.toString());
      String shPath = scriptFilePath + tablename + "_exec.sh";
      File shFile = new File(shPath);
      if (shFile.isFile() && shFile.exists()) {
         shFile.delete();
      }

      StringBuffer shContent = new StringBuffer();
      shContent.append("#!/bin/sh" + System.getProperty("line.separator"));
      shContent.append("fexp -c " + STR_FASTEXP_CHARACTER + " < " + scriptFilePath + scriptFileName);
      FileTool.writeContentToFile(shPath, shContent.toString());
      CommandTool.command("chmod -R 777 " + shPath);
      String curEndTime = DateTimeTool.getSysTime("");
      System.out.println("+++++++++++++++++++++++++++++>>>>>>>>>>>>>>end createTerdataPipes +++++++++++++++++++++++++++++" + curEndTime);
   }

   public static void createTerdataExportScript_new(Map<String, String> paramMap) {
      String curStartTime = DateTimeTool.getSysTime("");
      System.out.println("++++++++++++++++++++>>>>>>>>>>>>>>start createTerdataExportScript+++++++++++++++++++++++++++++ " + curStartTime);
      String taskname = (String)paramMap.get("taskname");
      String teradataServersIp = (String)paramMap.get("teradataServersIp");
      String teradataServersUser = (String)paramMap.get("teradataServersUser");
      String teradataServerspwd = (String)paramMap.get("teradataServerspwd");
      String schema = (String)paramMap.get("schema");
      String tablename = (String)paramMap.get("tablename");
      String colNamesStr = (String)paramMap.get("colNamesStr");
      String source_pipe_path = (String)paramMap.get("source_pipe_path");
      String pipeFileName = tablename + ".pipe";
      String scriptFileName = tablename + ".fx";
      File scriptFile = new File(source_pipe_path + scriptFileName);
      if (scriptFile.isFile() && scriptFile.exists()) {
         scriptFile.delete();
      }

      StringBuffer scptStr = new StringBuffer();
      scptStr.append(".LOGTABLE " + schema + "." + tablename + "_log;" + System.getProperty("line.separator"));
      scptStr.append(".LOGON " + teradataServersIp + "/" + teradataServersUser + "," + teradataServerspwd + ";" + System.getProperty("line.separator"));
      scptStr.append("DATABASE " + schema + ";" + System.getProperty("line.separator"));
      scptStr.append(".BEGIN EXPORT SESSIONS 4;" + System.getProperty("line.separator"));
      scptStr.append(".EXPORT OUTFILE " + source_pipe_path + pipeFileName + " MODE RECORD FORMAT TEXT;" + System.getProperty("line.separator"));
      scptStr.append("SELECT " + colNamesStr + "as export_cols FROM " + schema + "." + tablename + ";" + System.getProperty("line.separator"));
      scptStr.append(".END EXPORT;" + System.getProperty("line.separator"));
      scptStr.append(".LOGOFF;" + System.getProperty("line.separator"));
      System.out.println(">>>>>>>>>>>>>>script content:" + scptStr.toString());
      FileTool.writeContentToFile(source_pipe_path + scriptFileName, scptStr.toString());
      String shPath = source_pipe_path + tablename + ".sh";
      File shFile = new File(shPath);
      if (shFile.isFile() && shFile.exists()) {
         shFile.delete();
      }

      StringBuffer shContent = new StringBuffer();
      shContent.append("#!/bin/sh" + System.getProperty("line.separator"));
      shContent.append("fexp -c " + STR_FASTEXP_CHARACTER + " < " + source_pipe_path + scriptFileName + " > " + source_pipe_path + "/" + tablename + ".log");
      FileTool.writeContentToFile(shPath, shContent.toString());
      CommandTool.command("chmod -R 777 " + shPath);
      String curEndTime = DateTimeTool.getSysTime("");
      System.out.println("+++++++++++++++++++++++++++++>>>>>>>>>>>>>>end createTerdataPipes +++++++++++++++++++++++++++++" + curEndTime);
   }

   public static void delTerdataTaskFile(Map<String, String> paramMap) {
      String curStartTime = DateTimeTool.getSysTime("");
      System.out.println("++++++++++++++++++++>>>>>>>>>>>>>>start delTerdataTaskFile+++++++++++++++++++++++++++++ " + curStartTime);
      String taskname = (String)paramMap.get("taskname");
      String rmScriptFileCmd = "rm -rf " + STR_SCRIPTFILE_PATH + taskname + "/";
      CommandTool.command(rmScriptFileCmd);
      String rmPipeFileCmd = "rm -rf " + STR_PIPEFILE_PATH + taskname + "/";
      CommandTool.command(rmPipeFileCmd);
      String rmPipeFileTarCmd = "rm -rf " + STR_PIPEFILE_TAR_PATH + taskname + "/";
      CommandTool.command(rmPipeFileTarCmd);
      String curEndTime = DateTimeTool.getSysTime("");
      System.out.println("+++++++++++++++++++++++++++++>>>>>>>>>>>>>>end delTerdataTaskFile +++++++++++++++++++++++++++++" + curEndTime);
   }

   public static void createTerdataPipes(Map<String, String> paramMap) {
      String curStartTime = DateTimeTool.getSysTime("");
      System.out.println("++++++++++++++++++++>>>>>>>>>>>>>>start createTerdataPipes+++++++++++++++++++++++++++++ " + curStartTime);
      String tablename = (String)paramMap.get("tablename");
      String taskname = (String)paramMap.get("taskname");
      String pipeFilePath = STR_PIPEFILE_PATH + taskname + "/";
      String pipeFileName = tablename + ".pipe";
      String rmPipeFileCmd = "rm -f " + pipeFilePath + pipeFileName;
      String mkrPipeFileCmd = "mkfifo " + pipeFilePath + pipeFileName;
      CommandTool.command(rmPipeFileCmd);
      CommandTool.command(mkrPipeFileCmd);
      String pipeFileTarPath = STR_PIPEFILE_TAR_PATH + taskname + "/";
      String rmPipeFileTarCmd = "rm -f " + pipeFileTarPath + "tar_" + pipeFileName;
      String mkrPipeFileTarCmd = "mkfifo " + pipeFileTarPath + "tar_" + pipeFileName;
      CommandTool.command(rmPipeFileTarCmd);
      CommandTool.command(mkrPipeFileTarCmd);
      String curEndTime = DateTimeTool.getSysTime("");
      System.out.println("++++++++++++++++++++>>>>>>>>>>>>>>end createTerdataPipes+++++++++++++++++++++++++++++ " + curEndTime);
   }

   public static void execTerdataExportSh(Map<String, String> paramMap) {
      String curStartTime = DateTimeTool.getSysTime("");
      System.out.println("++++++++++++++++++++>>>>>>>>>>>>>>start execTerdataExportSh+++++++++++++++++++++++++++++ " + curStartTime);
      String tablename = (String)paramMap.get("tablename");
      String taskname = (String)paramMap.get("taskname");
      String scriptFilePath = STR_SCRIPTFILE_PATH + taskname + "/";
      String shPath = scriptFilePath + tablename + "_exec.sh";

      try {
         Runtime.getRuntime().exec(shPath);
      } catch (IOException e) {
         e.printStackTrace();
      }

      String curEndTime = DateTimeTool.getSysTime("");
      System.out.println("++++++++++++++++++++>>>>>>>>>>>>>>end execTerdataExportSh+++++++++++++++++++++++++++++ " + curEndTime);
   }

   public static String teradataTypetoVarchar(String colName, String colType, String colLength) {
      if (StringUtils.isNotBlank(colType)) {
         if ("DATE".equals(colType.toUpperCase())) {
            colName = "CAST(cast(" + colName + " as date format 'yyyy-mm-dd') AS VARCHAR(50))";
         } else if ("BYTEINT".equals(colType.toUpperCase())) {
            colName = "TRIM(" + colName + ")";
         } else if ("SMALLINT".equals(colType.toUpperCase())) {
            colName = "TRIM(" + colName + ")";
         } else if ("INTEGER".equals(colType.toUpperCase())) {
            colName = "TRIM(" + colName + ")";
         } else if ("BIGINT".equals(colType.toUpperCase())) {
            colName = "TRIM(" + colName + ")";
         } else if ("DECIMAL".equals(colType.toUpperCase())) {
            colName = "TRIM(TRIM(TRAILING '.' FROM " + colName + "))";
         } else if ("NUMERIC".equals(colType.toUpperCase())) {
            colName = "TRIM(TRIM(TRAILING '.' FROM " + colName + "))";
         } else if ("FLOAT".equals(colType.toUpperCase())) {
            colName = "TRIM(TRIM(TRAILING '.' FROM TRIM(TRAILING '0' FROM (cast((" + colName + "(format '-Z(22)Z.ZZZZZ')) as varchar(500)) ))))  ";
         } else if ("CHAR".equals(colType.toUpperCase())) {
            if (StringUtils.isNotBlank(colLength)) {
               colName = "CAST(" + colName + " AS VARCHAR(" + colLength + "))";
            }
         } else if ("TIME".equals(colType.toUpperCase())) {
            colName = "CAST(cast(" + colName + " as date format 'hh:mi:ss') AS VARCHAR(50))";
         } else if ("TIMESTAMP".equals(colType.toUpperCase())) {
            colName = "substring(CAST(" + colName + " AS VARCHAR(50)) from 1,19)";
         } else if ("BYTE".equals(colType.toUpperCase())) {
            colName = "";
         } else if ("BYTEINT".equals(colType.toUpperCase())) {
            colName = "";
         } else if ("LONG VARGRAPHIC".equals(colType.toUpperCase())) {
            colName = "";
         } else if ("RAPHIC".equals(colType.toUpperCase())) {
            colName = "";
         } else if ("REAL".equals(colType.toUpperCase())) {
            colName = "";
         } else if ("VARBYTE".equals(colType.toUpperCase())) {
            colName = "";
         } else if ("VARGRAPHIC".equals(colType.toUpperCase())) {
            colName = "";
         } else if ("ARRAY".equals(colType.toUpperCase())) {
            colName = "";
         } else if ("BLOB".equals(colType.toUpperCase())) {
            colName = "";
         } else if ("CLOB".equals(colType.toUpperCase())) {
            colName = "";
         } else if ("TIME WITH TIME ZONE".equals(colType.toUpperCase())) {
            colName = "";
         } else if ("TIMESTAMP WITH TIME ZONE".equals(colType.toUpperCase())) {
            colName = "";
         } else if (colType.toUpperCase().startsWith("INTERVAL")) {
            colName = "";
         } else if ("REAL".equals(colType.toUpperCase())) {
            colName = "";
         } else if ("DOUBLE PRECISION".equals(colType.toUpperCase())) {
            colName = "";
         } else if ("NUMBER".equals(colType.toUpperCase())) {
            colName = "";
         } else if ("XML".equals(colType.toUpperCase())) {
            colName = "";
         } else if ("TD_ANYTYPE".equals(colType.toUpperCase())) {
            colName = "";
         } else if (colType.toUpperCase().startsWith("ANYTYPE")) {
            colName = "";
         } else if ("VARIANT_TYPE".equals(colType.toUpperCase())) {
            colName = "";
         }
      }

      colName = "'\"'||coalesce(" + colName + ",'')||'\"'";
      return colName;
   }

   public static String teradataTypeLength(String colType, String colLength, String colScale) {
      if (StringUtils.isNotBlank(colType)) {
         if ("DATE".equals(colType.toUpperCase())) {
            colLength = "20";
         } else if ("BYTEINT".equals(colType.toUpperCase())) {
            colLength = "5";
         } else if ("SMALLINT".equals(colType.toUpperCase())) {
            colLength = "10";
         } else if ("INTEGER".equals(colType.toUpperCase())) {
            colLength = "15";
         } else if ("BIGINT".equals(colType.toUpperCase())) {
            colLength = "20";
         } else if ("DECIMAL".equals(colType.toUpperCase())) {
            if (StringUtils.isNotBlank(colLength) && StringUtils.isNotBlank(colScale)) {
               colLength = String.valueOf(Integer.valueOf(colLength) + Integer.valueOf(colScale) + 5);
            }
         } else if ("NUMERIC".equals(colType.toUpperCase())) {
            if (StringUtils.isNotBlank(colLength) && StringUtils.isNotBlank(colScale)) {
               colLength = String.valueOf(Integer.valueOf(colLength) + Integer.valueOf(colScale) + 5);
            }
         } else if ("FLOAT".equals(colType.toUpperCase())) {
            colLength = "500";
         } else if ("TIME".equals(colType.toUpperCase())) {
            colLength = "50";
         } else if ("TIMESTAMP".equals(colType.toUpperCase())) {
            colLength = "50";
         }
      }

      return colLength;
   }

   public static void createTerdataExportScriptByBTEQ(Map<String, String> paramMap) {
      String teradataServersIp = (String)paramMap.get("teradataServersIp");
      String teradataServersUser = (String)paramMap.get("teradataServersUser");
      String teradataServerspwd = (String)paramMap.get("teradataServerspwd");
      String schema = (String)paramMap.get("schema");
      String tablename = (String)paramMap.get("tablename");
      String colNamesStr = (String)paramMap.get("colNamesStr");
      String taskname = (String)paramMap.get("taskname");
      String pipeFilePath = STR_PIPEFILE_PATH + taskname + "/";
      String pipeFileTarPath = STR_PIPEFILE_TAR_PATH + taskname + "/";
      File sPath = new File(pipeFilePath);
      if (!sPath.exists()) {
         sPath.mkdirs();
      }

      File tarPath = new File(pipeFileTarPath);
      if (!tarPath.exists()) {
         tarPath.mkdirs();
      }

      String pipeFileName = tablename + ".pipe";
      String scriptFilePath = STR_SCRIPTFILE_PATH + taskname + "/";
      String scriptFileName = tablename + ".fx";
      File scriptFile = new File(scriptFilePath + scriptFileName);
      if (!scriptFile.exists() || !scriptFile.isFile()) {
         StringBuffer scptStr = new StringBuffer();
         scptStr.append(".WIDTH 1024;" + System.getProperty("line.separator"));
         scptStr.append(".LOGON " + teradataServersIp + "/" + teradataServersUser + "," + teradataServerspwd + ";" + System.getProperty("line.separator"));
         scptStr.append(".SET TITLEDASHES OFF;" + System.getProperty("line.separator"));
         scptStr.append(".EXPORT REPORT FILE='" + pipeFilePath + pipeFileName + "';" + System.getProperty("line.separator"));
         scptStr.append(".SET SEPARATOR '" + STR_COL_SPLIT_PATH + "';" + System.getProperty("line.separator"));
         scptStr.append("SELECT " + colNamesStr + "as export_cols FROM " + schema + "." + tablename + ";" + System.getProperty("line.separator"));
         scptStr.append(".EXPORT RESET;" + System.getProperty("line.separator"));
         scptStr.append(".LOGOFF;" + System.getProperty("line.separator"));
         scptStr.append(".EXIT;" + System.getProperty("line.separator"));
         System.out.println(">>>>>>>>>>>>>>script content:" + scptStr.toString());
         System.out.println(">>>>>>>>>>>>>>create script file:mkdir -p " + scriptFilePath + ";touch " + scriptFileName + ";");
         FileTool.writeContentToFile(scriptFilePath + scriptFileName, scptStr.toString());
      }

      String shPath = scriptFilePath + tablename + "_exec.sh";
      File shFile = new File(shPath);
      if (!shFile.exists() || !shFile.isFile()) {
         StringBuffer shContent = new StringBuffer();
         shContent.append("#!/bin/sh" + System.getProperty("line.separator"));
         shContent.append("bteq -c utf8 < " + scriptFilePath + scriptFileName);
         FileTool.writeContentToFile(shPath, shContent.toString());
         CommandTool.command("chmod -R 777 " + shPath);
      }

   }

   public static void deltrailingSpace(Map<String, String> paramMap) {
      String curStartTime = DateTimeTool.getSysTime("");
      System.out.println("++++++++++++++++++++>>>>>>>>>>>>>>start deltrailingSpace+++++++++++++++++++++++++++++ " + curStartTime);
      String tablename = (String)paramMap.get("tablename");
      String taskname = (String)paramMap.get("taskname");
      String scriptFilePath = STR_SCRIPTFILE_PATH + taskname + "/";
      String shPath1 = scriptFilePath + tablename + "_exec1.sh";
      CommandTool.command(shPath1);
      String curEndTime = DateTimeTool.getSysTime("");
      System.out.println("++++++++++++++++++++>>>>>>>>>>>>>>end deltrailingSpace+++++++++++++++++++++++++++++ " + curEndTime);
   }

   public static List<String> getLoalhostIP() {
      List<String> ls = new ArrayList();

      try {
         Enumeration<?> enumeration = NetworkInterface.getNetworkInterfaces();
         InetAddress ip = null;

         while(enumeration.hasMoreElements()) {
            NetworkInterface netInterface = (NetworkInterface)enumeration.nextElement();
            Enumeration<?> addresses = netInterface.getInetAddresses();

            while(addresses.hasMoreElements()) {
               ip = (InetAddress)addresses.nextElement();
               ls.add(ip.getHostName());
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }

      return ls;
   }

   static {
      Properties props = new Properties();

      try {
         props = PropertiesLoaderUtils.loadAllProperties("config.properties");
      } catch (IOException e) {
         e.printStackTrace();
      }

      STR_SCRIPTFILE_PATH = props.getProperty("exp_table_scriptfile_path");
      STR_PIPEFILE_PATH = props.getProperty("exp_table_pipefile_path");
      STR_PIPEFILE_TAR_PATH = props.getProperty("exp_table_pipefile_tar_path");
      STR_COL_SPLIT_PATH = props.getProperty("exp_table_teradata_col_split");
      STR_FASTEXP_CHARACTER = props.getProperty("fastexp_character");
      System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>TeradataTool static constant init finish>>>>>>>>>>>>>>");
   }
}
