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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chenyang.nse.bussiness.tools.net.SFTPUtil;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;

public class UnknownFileStruTool {
   public static final int maxReadLine = 10;
   public static final String sc = "[`~!#$%^&*()+=|{}':;',\\[\\]<>/?~！#￥%……&*（）——+|{}【】‘；：”“’\"。，、？]";
   public static final String[] other = new String[]{"xml", "txt", "xls", "xlsx", "csv", "json", ""};

   public static Map<String, List<String>> getFileByPath(String path, String codepage) throws IOException {
      String result = "";
      Map<String, List<String>> sp = new HashMap();
      File file = new File(path);
      String fileTyle = getSuffiex(path);
      if (isExcel(fileTyle)) {
         sp.put("6", null);
         return sp;
      } else if (isCsv(fileTyle)) {
         sp.put("7", null);
         return sp;
      } else if (isOther(fileTyle)) {
         sp.put("0", null);
         return sp;
      } else {
         InputStreamReader read = new InputStreamReader(new FileInputStream(file), codepage);
         BufferedReader bufferedReader = new BufferedReader(read);
         String line = "";
         int i = 0;
         List<String> list = new ArrayList();
         List<String> sepList = new ArrayList();

         StringBuilder json;
         for(json = new StringBuilder(); (line = bufferedReader.readLine()) != null; ++i) {
            json.append(line);
            if (i < 10) {
               list.add(countSeparation(line));
               sepList.add(containSeparation(line));
            } else if (i == 10) {
               if (isMonospaced(list)) {
                  List resultList = new ArrayList(((String)list.get(0)).split(" ").length);
                  Collections.addAll(resultList, ((String)list.get(0)).split(" "));
                  if ("0".equals(resultList.get(0))) {
                     resultList.remove(0);
                  }

                  sp.put("1", resultList);
                  read.close();
                  bufferedReader.close();
                  return sp;
               }

               if (isSeparation(sepList)) {
                  sp.put("2", null);
                  read.close();
                  bufferedReader.close();
                  return sp;
               }
            }
         }

         read.close();
         bufferedReader.close();
         if (1 < i && i <= 10) {
            if (isMonospaced(list)) {
               List resultList = new ArrayList(((String)list.get(0)).split(" ").length);
               Collections.addAll(resultList, ((String)list.get(0)).split(" "));
               if ("0".equals(resultList.get(0))) {
                  resultList.remove(0);
               }

               if (resultList.size() == 0) {
                  sp.put("0", null);
               } else {
                  sp.put("1", resultList);
               }

               return sp;
            }

            if (isSeparation(sepList)) {
               sp.put("2", null);
               return sp;
            }
         }

         List<Object> json2 = isJson(json.toString());
         if ((Boolean)json2.get(0)) {
            List<String> contentlist = new ArrayList();
            if (json2.get(1) != null) {
               contentlist.add(json2.get(1).toString());
            } else {
               contentlist.add("");
            }

            sp.put("3", contentlist);
            return sp;
         } else if (isXml(file)) {
            sp.put("4", null);
            return sp;
         } else {
            sp.put("0", null);
            return sp;
         }
      }
   }

   public static Map<String, List<String>> getFtpFileByPath(FTPClient ftp, String path, String codepage, String filename, String fileurl) throws IOException {
      String result = "";
      Map<String, List<String>> sp = new HashMap();
      String fileTyle = getSuffiex(path);
      if (isExcel(fileTyle)) {
         sp.put("6", null);
         return sp;
      } else if (isCsv(fileTyle)) {
         sp.put("7", null);
         return sp;
      } else if (isOther(fileTyle)) {
         sp.put("0", null);
         return sp;
      } else {
         ftp.enterLocalPassiveMode();
         ftp.changeWorkingDirectory(fileurl);
         InputStream inputStream = ftp.retrieveFileStream(filename);
         if (inputStream == null) {
            sp.put("0", null);
            if (inputStream != null) {
               inputStream.close();
               ftp.completePendingCommand();
            }

            return sp;
         } else {
            InputStreamReader read = new InputStreamReader(inputStream, codepage);
            BufferedReader bufferedReader = new BufferedReader(read);
            String line = "";
            int i = 0;
            List<String> list = new ArrayList();
            List<String> sepList = new ArrayList();

            StringBuilder json;
            for(json = new StringBuilder(); (line = bufferedReader.readLine()) != null; ++i) {
               json.append(line);
               if (i < 10) {
                  list.add(countSeparation(line));
                  sepList.add(containSeparation(line));
               } else {
                  if (i != 10) {
                     break;
                  }

                  if (isMonospaced(list)) {
                     List resultList = new ArrayList(((String)list.get(0)).split(" ").length);
                     Collections.addAll(resultList, ((String)list.get(0)).split(" "));
                     if ("0".equals(resultList.get(0))) {
                        resultList.remove(0);
                     }

                     sp.put("1", resultList);
                     if (bufferedReader != null) {
                        bufferedReader.close();
                     }

                     if (read != null) {
                        read.close();
                     }

                     if (inputStream != null) {
                        inputStream.close();
                        ftp.completePendingCommand();
                     }

                     return sp;
                  }

                  if (isSeparation(sepList)) {
                     sp.put("2", null);
                     if (bufferedReader != null) {
                        bufferedReader.close();
                     }

                     if (read != null) {
                        read.close();
                     }

                     if (inputStream != null) {
                        inputStream.close();
                        ftp.completePendingCommand();
                     }

                     return sp;
                  }
               }
            }

            bufferedReader.close();
            read.close();
            inputStream.close();
            ftp.completePendingCommand();
            if (1 < i && i <= 10) {
               if (isMonospaced(list)) {
                  List resultList = new ArrayList(((String)list.get(0)).split(" ").length);
                  Collections.addAll(resultList, ((String)list.get(0)).split(" "));
                  if ("0".equals(resultList.get(0))) {
                     resultList.remove(0);
                  }

                  sp.put("1", resultList);
                  return sp;
               }

               if (isSeparation(sepList)) {
                  sp.put("2", null);
                  return sp;
               }
            }

            List<Object> json2 = isJson(json.toString());
            ftp.enterLocalPassiveMode();
            ftp.changeWorkingDirectory(fileurl);
            InputStream is = ftp.retrieveFileStream(filename);
            if ((Boolean)json2.get(0)) {
               List<String> contentlist = new ArrayList();
               String content = json2.get(1).toString();
               contentlist.add(content);
               sp.put("3", contentlist);
               if (is != null) {
                  is.close();
                  ftp.completePendingCommand();
               }

               return sp;
            } else if (isXml(is)) {
               sp.put("4", null);
               if (is != null) {
                  is.close();
                  ftp.completePendingCommand();
               }

               return sp;
            } else {
               sp.put("0", null);
               if (is != null) {
                  is.close();
                  ftp.completePendingCommand();
               }

               return sp;
            }
         }
      }
   }

   public static Map<String, List<String>> getSftpFileByPath(String path, String codepage, SFTPUtil sftp) throws Exception {
      Map<String, List<String>> sp = new HashMap();
      String fileTyle = getSuffiex(path);
      if (isExcel(fileTyle)) {
         sp.put("6", null);
         return sp;
      } else if (isCsv(fileTyle)) {
         sp.put("7", null);
         return sp;
      } else if (isOther(fileTyle)) {
         sp.put("0", null);
         return sp;
      } else {
         InputStream is = sftp.getInputStream(path);
         InputStreamReader isr = new InputStreamReader(is, codepage);
         BufferedReader bufferedReader = new BufferedReader(isr);
         String line = "";
         int i = 0;
         List<String> list = new ArrayList();
         List<String> sepList = new ArrayList();

         StringBuilder json;
         for(json = new StringBuilder(); (line = bufferedReader.readLine()) != null; ++i) {
            json.append(line);
            if (i < 10) {
               list.add(countSeparation(line));
               sepList.add(containSeparation(line));
            } else if (i == 10) {
               if (isMonospaced(list)) {
                  List resultList = new ArrayList(((String)list.get(0)).split(" ").length);
                  Collections.addAll(resultList, ((String)list.get(0)).split(" "));
                  if ("0".equals(resultList.get(0))) {
                     resultList.remove(0);
                  }

                  sp.put("1", resultList);
                  bufferedReader.close();
                  is.close();
                  return sp;
               }

               if (isSeparation(sepList)) {
                  sp.put("2", null);
                  bufferedReader.close();
                  is.close();
                  return sp;
               }
            }
         }

         if (1 < i && i <= 10) {
            if (isMonospaced(list)) {
               List resultList = new ArrayList(((String)list.get(0)).split(" ").length);
               Collections.addAll(resultList, ((String)list.get(0)).split(" "));
               if ("0".equals(resultList.get(0))) {
                  resultList.remove(0);
               }

               sp.put("1", resultList);
               bufferedReader.close();
               is.close();
               return sp;
            }

            if (isSeparation(sepList)) {
               sp.put("2", null);
               bufferedReader.close();
               is.close();
               return sp;
            }
         }

         List<Object> json2 = isJson(json.toString());
         InputStream dataInputStream = sftp.getDataInputStream(path);
         if ((Boolean)json2.get(0)) {
            List<String> contentlist = new ArrayList();
            String content = json2.get(1).toString();
            contentlist.add(content);
            sp.put("3", contentlist);
            dataInputStream.close();
            bufferedReader.close();
            is.close();
            return sp;
         } else if (isXml(dataInputStream)) {
            sp.put("4", null);
            dataInputStream.close();
            bufferedReader.close();
            is.close();
            return sp;
         } else {
            sp.put("0", null);
            dataInputStream.close();
            bufferedReader.close();
            is.close();
            return sp;
         }
      }
   }

   public static boolean isMonospaced(List<String> list) {
      long count = list.stream().distinct().count();
      boolean isRepeat = count == 1L;
      return isRepeat;
   }

   public static boolean isSeparation(List<String> list) {
      long count = list.stream().distinct().count();
      boolean isRepeat = count == 1L;
      return isRepeat;
   }

   public static String containSeparation(String str) {
      StringBuilder strs = new StringBuilder();
      Pattern p = Pattern.compile("[`~!#$%^&*()+=|{}':;',\\[\\]<>/?~！#￥%……&*（）——+|{}【】‘；：”“’\"。，、？]");
      Matcher m = p.matcher(str);

      while(m.find()) {
         strs.append(m.group());
      }

      return strs.toString();
   }

   public static String replaceSeparation(String str, String sep) {
      if (str == null) {
         return null;
      } else {
         Pattern p = Pattern.compile("[`~!#$%^&*()+=|{}':;',\\[\\]<>/?~！#￥%……&*（）——+|{}【】‘；：”“’\"。，、？]");
         Matcher m = p.matcher(str);
         String skuName = m.replaceAll(sep).replaceAll(" +", " ");
         return skuName.trim();
      }
   }

   public static String countSeparation(String str) {
      StringBuilder strs = new StringBuilder();
      Pattern p = Pattern.compile("[`~!#$%^&*()+=|{}':;',\\[\\]<>/?~！#￥%……&*（）——+|{}【】‘；：”“’\"。，、？]");
      Matcher m = p.matcher(str);
      String skuName = m.replaceAll(" ").replaceAll(" +", " ");
      String[] s = skuName.split(" ");

      for(int i = 0; i < s.length; ++i) {
         strs.append(s[i].length() + " ");
      }

      return strs.toString();
   }

   public static List<Object> isJson(String content) {
      List<Object> list = new ArrayList();

      try {
         if ("".equals(content)) {
            list.add(false);
            list.add(null);
         }

         JSONArray jsonStr = JSONObject.parseArray(content);
         list.add(true);
         list.add(content);
      } catch (Exception var5) {
         try {
            JSONObject jsonStr = JSONObject.parseObject(content);
            list.add(true);
            list.add(content);
         } catch (Exception var4) {
            list.add(false);
            list.add(null);
         }
      }

      return list;
   }

   public static boolean isXml(File file) {
      try {
         DocumentBuilderFactory foctory = DocumentBuilderFactory.newInstance();
         DocumentBuilder builder = foctory.newDocumentBuilder();
         builder.parse(file);
         return true;
      } catch (Exception var3) {
         return false;
      }
   }

   public static boolean isXml(InputStream inputStream) {
      try {
         DocumentBuilderFactory foctory = DocumentBuilderFactory.newInstance();
         DocumentBuilder builder = foctory.newDocumentBuilder();
         builder.parse(inputStream);
         return true;
      } catch (Exception var3) {
         return false;
      }
   }

   public static boolean isExcel(String fileTyle) {
      return "xlsx".equals(fileTyle) || "xls".equals(fileTyle);
   }

   public static boolean isCsv(String fileTyle) {
      return "csv".equals(fileTyle);
   }

   public static boolean isOther(String fileTyle) {
      return !Arrays.asList(other).contains(fileTyle);
   }

   private static String getSuffiex(String filepath) {
      if (StringUtils.isBlank(filepath)) {
         return "";
      } else {
         int index = filepath.lastIndexOf(".");
         return index == -1 ? "" : filepath.substring(index + 1, filepath.length());
      }
   }

   public static String getFileContent(String path, String codepage) throws Exception {
      StringBuffer sb = new StringBuffer();
      File file = new File(path);
      FileInputStream fis = new FileInputStream(file);
      InputStreamReader read = new InputStreamReader(fis, codepage);
      BufferedReader bufferedReader = new BufferedReader(read);
      String line = "";

      for(int i = 0; (line = bufferedReader.readLine()) != null; ++i) {
         if (i < 5) {
            sb.append(line);
            sb.append("^||^");
         }
      }

      if (bufferedReader != null) {
         bufferedReader.close();
      }

      if (read != null) {
         read.close();
      }

      if (fis != null) {
         fis.close();
      }

      if (sb.toString().length() > 20000) {
         return sb.toString().substring(20000);
      } else {
         return sb.toString();
      }
   }

   public static String getFileContentSFTP(String path, String codepage, SFTPUtil sftp) throws Exception {
      StringBuffer sb = new StringBuffer();
      InputStream is = null;
      InputStreamReader isr = null;
      BufferedReader bufferedReader = null;

      try {
         is = sftp.getInputStream(path);
         isr = new InputStreamReader(is, codepage);
         bufferedReader = new BufferedReader(isr);
         String line = "";

         for(int i = 0; (line = bufferedReader.readLine()) != null && i < 5; ++i) {
            sb.append(line);
            sb.append("^||^");
         }
      } catch (Exception var12) {
      } finally {
         if (bufferedReader != null) {
            bufferedReader.close();
         }

         if (isr != null) {
            isr.close();
         }

         if (is != null) {
            is.close();
         }

      }

      return sb.toString().length() > 20000 ? sb.toString().substring(20000) : sb.toString();
   }

   public static String getFileContentFTP(FTPClient ftp, String path, String filename, String fileurl, String codepage) throws Exception {
      StringBuffer sb = new StringBuffer();
      InputStreamReader isr = null;
      BufferedReader br = null;
      ftp.enterLocalPassiveMode();
      ftp.changeWorkingDirectory(fileurl);
      InputStream inputStream = ftp.retrieveFileStream(filename);
      if (inputStream != null) {
         isr = new InputStreamReader(inputStream, codepage);
         br = new BufferedReader(isr);
         String line = "";

         for(int i = 0; (line = br.readLine()) != null; ++i) {
            if (i < 5) {
               sb.append(line);
               sb.append("^||^");
            }
         }
      }

      if (br != null) {
         br.close();
      }

      if (isr != null) {
         isr.close();
      }

      if (inputStream != null) {
         inputStream.close();
         ftp.completePendingCommand();
      }

      return sb.toString().length() > 20000 ? sb.toString().substring(20000) : sb.toString();
   }

   public static void main(String[] args) throws IOException {
      String path = "C:\\Users\\Administrator\\Desktop\\219\\ip_invpty1000.xml";
      System.out.println(getFileByPath(path, "UTF-16BE"));
   }
}
