package com.chenyang.nse.bussiness.engine.infa.powercenter961.pubtool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.sql.Clob;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class StringUtil {
   public static String removeAllSpecChars(String input, String spec) {
      if (isBlank(input)) {
         return "";
      } else {
         int index = input.lastIndexOf(spec);
         return input.substring(index + 1, input.length());
      }
   }

   public static Map gainResultMapByList(List<Map> keyItemInfo, String key) throws Exception {
      Map resutMap = new LinkedHashMap();

      for(Map map : keyItemInfo) {
         String mapKey = null2String(map.get(key));
         if (resutMap.get(mapKey) == null) {
            resutMap.put(mapKey, new ArrayList());
         }

         ((List)resutMap.get(mapKey)).add(map);
      }

      return resutMap;
   }

   public static boolean checkSameElementInVector(Vector vec) {
      if (vec != null && vec.size() != 0) {
         boolean status = false;

         for(int i = 0; i < vec.size(); ++i) {
            String str1 = vec.get(i).toString();
            if (i + 1 < vec.size()) {
               for(int k = i + 1; k < vec.size(); ++k) {
                  String str2 = vec.get(k).toString();
                  if (str1.equals(str2)) {
                     status = true;
                     k = vec.size();
                     i = k;
                  }
               }
            }
         }

         return status;
      } else {
         return false;
      }
   }

   public static String exToString(Exception ex) {
      String message = "";

      try {
         StringWriter sw = new StringWriter();
         PrintWriter pw = new PrintWriter(sw);
         ex.printStackTrace(pw);
         message = sw.toString();
         if (pw != null) {
            pw.close();
         }

         if (sw != null) {
            sw.close();
         }
      } catch (Exception e) {
         e.printStackTrace();
      }

      return message;
   }

   public static String null2String(Object obj) {
      return obj == null ? "" : obj.toString();
   }

   public static String null2Space(Object obj) {
      return obj == null ? " " : obj.toString();
   }

   public static String null2nbsp(Object obj) {
      return obj == null ? "&nbsp;" : obj.toString();
   }

   public static String null2Zero(Object obj) {
      return obj == null ? "0.00" : obj.toString();
   }

   public static String null2ZeroInt(Object obj) {
      return obj == null ? "0" : obj.toString();
   }

   public static String null2flag(Object obj) {
      return obj == null ? "--" : obj.toString();
   }

   public static double nulltoDouble(Object obj) {
      return obj == null ? (double)0.0F : Double.parseDouble(obj.toString());
   }

   public static List getTokens(String str, String delim) {
      if (str == null) {
         throw new IllegalArgumentException("string is null.");
      } else if (delim == null) {
         throw new IllegalArgumentException("delim is null.");
      } else {
         StringTokenizer tokenizer = new StringTokenizer(str, delim);
         List list = new ArrayList();

         while(tokenizer.hasMoreTokens()) {
            String tokens = tokenizer.nextToken();
            list.add(tokens);
         }

         return list;
      }
   }

   public static boolean isBlank(String inputValue) {
      return inputValue == null || "".equals(inputValue.trim());
   }

   public static boolean isEmail(String email) {
      if (email != null && !email.trim().equals("")) {
         String lString = "^(([0-9a-zA-Z]+)|([0-9a-zA-Z]+[_.0-9a-zA-Z-]*[0-9a-zA-Z]+))@([a-zA-Z0-9-]+[.])([a-zA-Z]*[a-zA-Z]+)";
         Pattern lPattern = Pattern.compile(lString);
         Matcher lMatcher = lPattern.matcher(email);
         return lMatcher.matches();
      } else {
         return false;
      }
   }

   public static boolean isMoney(String val) {
      char[] ca = val.toCharArray();

      for(int i = 0; i < ca.length; ++i) {
         char c = ca[i];
         if (c == '.') {
            return true;
         }

         if (c < '0' || c > '9') {
            return false;
         }
      }

      return true;
   }

   public static String getFristUpStr(String tableName) {
      String mehodStr = null;
      String[] tableAlias = null;
      String temp = "";
      if (tableName != null) {
         tableAlias = tableName.split("_");

         for(int i = 0; i < tableAlias.length; ++i) {
            char oldChar = tableAlias[i].charAt(0);
            char newChar = (oldChar + "").toUpperCase().charAt(0);
            temp = temp + tableAlias[i].replace(oldChar, newChar);
         }

         mehodStr = temp;
      }

      return mehodStr;
   }

   public static boolean isNumeric(String val) {
      char[] ca = val.toCharArray();

      for(int i = 0; i < ca.length; ++i) {
         char c = ca[i];
         if (c < '0' || c > '9') {
            return false;
         }
      }

      return true;
   }

   public static String returnRandomNumber(int length) {
      String sPswd = "";
      int iIndex = 0;
      String sChars = "1234567890";
      Random x = new Random();

      for(int i = 0; i < length; ++i) {
         iIndex = x.nextInt(9) + 1;
         sPswd = sPswd + sChars.substring(iIndex, iIndex + 1);
      }

      return sPswd;
   }

   public static String returnRandomString(int length) {
      String sPswd = "";
      int iIndex = 0;
      String sChars = "ab1cd2ef3gh4ijk5lmn6op7qr8st9uvw0xyz";
      Random x = new Random();

      for(int i = 0; i < length; ++i) {
         iIndex = x.nextInt(9) + 1;
         sPswd = sPswd + sChars.substring(iIndex, iIndex + 1);
      }

      System.out.println("==//random string is " + sPswd);
      return sPswd;
   }

   public static String returnRequestWebPath(HttpServletRequest request) {
      String ipath = request.getLocalAddr();
      int port = request.getLocalPort();
      String path = "http://" + ipath + ":" + port + request.getContextPath();
      return path;
   }

   public static String encodeBase64String(String str) throws IOException {
      BASE64Encoder encoder = new BASE64Encoder();
      String encodedStr = new String(encoder.encodeBuffer(str.getBytes()));
      return encodedStr.trim();
   }

   public static String dncodeBase64String(String str) throws IOException {
      BASE64Decoder dncoder = new BASE64Decoder();
      String encodedStr = new String(dncoder.decodeBuffer(str));
      return encodedStr.trim();
   }

   public static String toUtf8String(String s) {
      StringBuffer sb = new StringBuffer();

      for(int i = 0; i < s.length(); ++i) {
         char c = s.charAt(i);
         if (c >= 0 && c <= 255) {
            sb.append(c);
         } else {
            byte[] b;
            try {
               b = Character.toString(c).getBytes("utf-8");
            } catch (Exception ex) {
               System.out.println(ex);
               b = new byte[0];
            }

            for(int j = 0; j < b.length; ++j) {
               int k = b[j];
               if (k < 0) {
                  k += 256;
               }

               sb.append("%" + Integer.toHexString(k).toUpperCase());
            }
         }
      }

      return sb.toString();
   }

   public static int add(int a) {
      int ret = 0;
      if (a != 0 && a != 1) {
         return add(a - 1) + a;
      } else {
         ret += a;
         return ret;
      }
   }

   public static int getsConditionCount(String sCondition) {
      int length = 0;
      String[] whereValue = sCondition.split("where");
      if (whereValue.length > 1) {
         String[] andValue = sCondition.split("and");
         if (andValue.length > 1) {
            length = andValue.length - 1;
         } else {
            length = andValue.length;
         }
      }

      return length;
   }

   public static String get_string_order(String order) {
      String revalue = order;
      int value = Integer.parseInt(order);
      if (value >= 1 && value <= 9) {
         revalue = "00" + value;
      } else if (value >= 10 && value <= 99) {
         revalue = "0" + value;
      }

      return revalue;
   }

   public static String transdyh(String a) {
      String revalue = a.replace("'", "''");
      return revalue;
   }

   public static String to_money(String money) {
      if (money == null || money.equals("") || money.equals("--") || money.equals("null")) {
         money = "0.00";
      }

      Double dm = Double.valueOf(money);
      DecimalFormat fmt = new DecimalFormat("##0.00");
      return fmt.format(dm);
   }

   public static String repairZero(int order, int orgValue) {
      int digitNum = 0;
      String digitValue = "";
      if (String.valueOf(orgValue).length() >= order) {
         return String.valueOf(orgValue);
      } else {
         digitNum = order - String.valueOf(orgValue).length();

         for(int j = 0; j < digitNum; ++j) {
            digitValue = digitValue + "0";
         }

         return String.valueOf(digitValue + orgValue);
      }
   }

   public static String dbRepairZero(int order, String orgValue) {
      String rtnValue = "";
      int digitNum = 0;
      String digitValue = "";
      String singleRtnVle = "";
      int i = 0;
      int repairNum = 3;
      int j = 0;
      String[] divStr = orgValue.split("-");
      if (divStr.length <= 2) {
         singleRtnVle = "";

         for(int var15 = 0; var15 < order; ++var15) {
            singleRtnVle = singleRtnVle + "000";
         }

         return String.valueOf(singleRtnVle);
      } else {
         for(int var13 = 2; var13 < divStr.length; ++var13) {
            int singleNum = repairNum - divStr[var13].length();
            singleRtnVle = "";
            if (singleNum <= 0) {
               rtnValue = rtnValue + divStr[var13];
            } else {
               for(int var16 = 0; var16 < singleNum; ++var16) {
                  singleRtnVle = singleRtnVle + "0";
               }

               rtnValue = rtnValue + singleRtnVle + divStr[var13];
            }
         }

         if (divStr.length - 2 < order) {
            singleRtnVle = "";
            int repairnoenougu = order - (divStr.length - 2);

            for(int var14 = 0; var14 < repairnoenougu; ++var14) {
               singleRtnVle = singleRtnVle + "000";
            }
         }

         return rtnValue + singleRtnVle;
      }
   }

   public static String getOperOrder(String order) {
      String sing = "";
      String[] str = order.split("-");
      if (str.length >= 2) {
         for(int j = 2; j < str.length; ++j) {
            if (j == 2) {
               sing = str[j];
            } else {
               sing = sing + "-" + str[j];
            }
         }
      }

      if (!sing.equals("")) {
         sing = sing + "、";
      }

      return sing;
   }

   public static String coverRomanOrder(String order) {
      if (null != order && !"".equals(order)) {
         if (order.equals("1")) {
            return "Ⅰ";
         }

         if (order.equals("2")) {
            return "Ⅱ";
         }

         if (order.equals("3")) {
            return "Ⅲ";
         }

         if (order.equals("4")) {
            return "Ⅳ";
         }

         if (order.equals("5")) {
            return "Ⅴ";
         }
      }

      return "Ⅰ";
   }

   public static String oracleClob2Str(Clob clob) {
      try {
         return clob != null ? clob.getSubString(1L, (int)clob.length()) : null;
      } catch (SQLException e) {
         e.printStackTrace();
         return null;
      }
   }

   public static String delHtmlTag(String htmlStr) {
      String regEx_html = "<[^>]+>";
      Pattern p_html = Pattern.compile(regEx_html, 2);
      Matcher m_html = p_html.matcher(htmlStr);
      htmlStr = m_html.replaceAll("");
      Pattern n_html = Pattern.compile("&nbsp;", 2);
      Matcher mn_html = n_html.matcher(htmlStr);
      htmlStr = mn_html.replaceAll("");
      return htmlStr;
   }

   public static String addSpace(int length) {
      String ret = "";

      for(int i = 0; i < length * 4; ++i) {
         ret = ret.concat("&nbsp;");
      }

      return ret;
   }

   public static void writeToFile(String filePath, String fileName, String content) throws Exception {
      FileOutputStream fos = null;
      Writer out = null;

      try {
         File file = new File(filePath);
         if (!file.exists()) {
            file.mkdir();
         }

         fos = new FileOutputStream(filePath + fileName);
         out = new OutputStreamWriter(fos, "UTF-8");
         out.write(content);
      } catch (IOException e) {
         out.close();
         fos.close();
         e.printStackTrace();
         throw new IOException("读写异常");
      }

      out.close();
      fos.close();
   }

   public static String getTitleFieldName(String coverStr, String flag) {
      String rtnStr = "";
      String[][] str = getTitleInfoBySplit(coverStr);
      String[] str1 = str[0];

      for(int i = 0; i < str1.length; ++i) {
         if (flag.equals("0")) {
            rtnStr = rtnStr + "," + str1[i];
         } else {
            rtnStr = rtnStr + ",'" + str1[i] + "'";
         }
      }

      return rtnStr.replaceFirst(",", "");
   }

   public static void main(String[] args) {
      long dt = Long.parseLong("2099734149");
      System.out.println(iplongToIp(dt));
      System.out.println(getFristUpStr("clf_str_str"));
      String[][] str = getTitleInfoBySplit("TEST@中文1,TEST2@中文2");
      System.out.println(str);
      String[] str1 = str[0];

      for(int i = 0; i < str1.length; ++i) {
         System.out.println(str1[i]);
      }

      System.out.println("(" + getTitleFieldName("TEST@中文1,TEST2@中文2", "0") + ")");
      System.out.println("(" + getTitleFieldName("TEST@中文1,TEST2@中文2", "1") + ")");
   }

   public static String iplongToIp(long ipaddress) {
      StringBuffer sb = new StringBuffer("");
      sb.append(String.valueOf(ipaddress >>> 24));
      sb.append(".");
      sb.append(String.valueOf((ipaddress & 16777215L) >>> 16));
      sb.append(".");
      sb.append(String.valueOf((ipaddress & 65535L) >>> 8));
      sb.append(".");
      sb.append(String.valueOf(ipaddress & 255L));
      return sb.toString();
   }

   public long ipStrToLong(String ipaddress) {
      long[] ip = new long[4];
      int position1 = ipaddress.indexOf(".");
      int position2 = ipaddress.indexOf(".", position1 + 1);
      int position3 = ipaddress.indexOf(".", position2 + 1);
      ip[0] = Long.parseLong(ipaddress.substring(0, position1));
      ip[1] = Long.parseLong(ipaddress.substring(position1 + 1, position2));
      ip[2] = Long.parseLong(ipaddress.substring(position2 + 1, position3));
      ip[3] = Long.parseLong(ipaddress.substring(position3 + 1));
      return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
   }

   public static String upperTheFirstLetter(String str) {
      return str.replaceFirst(str.substring(0, 1), str.substring(0, 1).toUpperCase());
   }

   public static String[][] getTitleInfoBySplit(String coverStr, String firstSeparator, String secondSeparator) {
      String[][] dataTitle = (String[][])null;
      String[] colA = coverStr.split(firstSeparator);
      dataTitle = new String[2][colA.length];

      for(int j = 0; j < colA.length; ++j) {
         String[] nameValue = colA[j].split(secondSeparator);

         for(int k = 0; k < 2; ++k) {
            dataTitle[k][j] = nameValue[k];
         }
      }

      return dataTitle;
   }

   public static String[][] getTitleInfoBySplit(String coverStr) {
      String[][] dataTitle = (String[][])null;
      String[] colA = coverStr.split(",");
      dataTitle = new String[2][colA.length];

      for(int j = 0; j < colA.length; ++j) {
         String[] nameValue = colA[j].split("@");

         for(int k = 0; k < 2; ++k) {
            dataTitle[k][j] = nameValue[k];
         }
      }

      return dataTitle;
   }

   public static String[][] getTitleInfoBySplit(String coverStr, String firstSeparator, String secondSeparator, String threeSeparator) {
      String[][] dataTitle = (String[][])null;
      String[] colA = coverStr.split(firstSeparator);
      dataTitle = new String[2][colA.length];

      for(int j = 0; j < colA.length; ++j) {
         String[] nameValue = colA[j].split(secondSeparator);
         String[] value = nameValue[0].split(threeSeparator);
         dataTitle[0][j] = value[0];
         dataTitle[1][j] = nameValue[1];
      }

      return dataTitle;
   }

   public static String[] listToArray(List<String> list) {
      String[] array = new String[list.size()];

      for(int i = 0; i < list.size(); ++i) {
         array[i] = (String)list.get(i);
      }

      return array;
   }

   public static String[] gainSelectField(String sql) throws Exception {
      System.out.println(sql);
      String[] column = sql.split("FROM");
      String[] columnStr = column[0].split(" ,");
      String[] rtnColumn = new String[columnStr.length];

      for(int i = 0; i < columnStr.length; ++i) {
         String[] columnCol = columnStr[i].split(" ");
         rtnColumn[i] = columnCol[columnCol.length - 1];
      }

      return rtnColumn;
   }

   public static String converStringOrder(String orgStr, String flag) throws Exception {
      String s1 = "";
      String[] argt = orgStr.split(flag);

      for(int i = argt.length - 1; i >= 0; --i) {
         if (i != argt.length - 1) {
            s1 = s1 + flag;
         }

         s1 = s1 + argt[i];
      }

      return s1;
   }

   public static String getFilePath() {
      String path = StringUtil.class.getClassLoader().getResource("").getPath();
      String exePath = path.subSequence(1, path.length() - 16) + "cert/";
      return exePath;
   }

   public static String[] getTRANSFORMFIELDDataType(String dataType, String dataLength) {
      String[] colomnType = new String[3];
      String type = dataType.toLowerCase();
      int clength = 0;
      int tr_scale = 0;
      if (type.equals("date")) {
         clength = 29;
         tr_scale = 9;
      } else {
         clength = Integer.parseInt(dataLength);
      }

      if (type.equals("char")) {
         type = type.replaceAll("char", "string");
      } else if (type.equals("number")) {
         type = type.replaceAll("number", "decimal");
      } else if (type.equals("date")) {
         type = type.replaceAll("date", "date/time");
      } else if (type.equals("varchar2")) {
         type = type.replaceAll("varchar2", "string");
      } else if (type.equals("nvarchar2")) {
         type = type.replaceAll("nvarchar2", "nstring");
      } else if (type.equals("blob")) {
         type = type.replaceAll("blob", "binary");
      } else if (type.equals("clob")) {
         type = type.replaceAll("clob", "text");
      } else if (type.indexOf("timestamp") != -1) {
         type = "timestamp";
      }

      colomnType[0] = type + "";
      colomnType[1] = clength + "";
      colomnType[2] = tr_scale + "";
      return colomnType;
   }

   public static String[] getTARGETFIELD(String dataType, String dataLength) {
      String[] str = new String[2];
      String type = dataType.toLowerCase();
      int clength = 0;
      if (type.equals("date")) {
         clength = 19;
      } else {
         clength = Integer.parseInt(dataLength);
      }

      if (type.equals("number")) {
         type = type.replaceAll("number", "number(p,s)");
      } else if (type.indexOf("timestamp") != -1) {
         type = "timestamp";
      }

      str[0] = type;
      str[1] = clength + "";
      return str;
   }

   public static String[] getSOURCEFIELD(String dataType, String dataLen) {
      String[] typeAndLen = new String[3];
      dataType = dataType.toLowerCase();
      typeAndLen[0] = dataType;
      typeAndLen[1] = dataLen;
      typeAndLen[2] = dataLen;
      if (dataType.equals("number")) {
         typeAndLen[0] = "number(p,s)";
         typeAndLen[1] = "24";
      } else if (dataType.indexOf("timestamp") != -1) {
         typeAndLen[0] = "timestamp";
         typeAndLen[1] = "19";
         typeAndLen[2] = "26";
      } else if (dataType.equals("date")) {
         typeAndLen[1] = "19";
         typeAndLen[2] = "19";
      }

      return typeAndLen;
   }
}
