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

import com.chenyang.nse.bussiness.tools.net.SFTPUtil;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadExcelTool {
   public static final String OFFICE_EXCEL_XLS = "xls";
   public static final String OFFICE_EXCEL_XLSX = "xlsx";

   public static Map<String, List<String>> readExcel(String filepath) throws EncryptedDocumentException, InvalidFormatException, IOException {
      Workbook workbook = getWorkbook(filepath);
      Map<String, List<String>> map = new HashMap();
      if (workbook != null) {
         int numberOfSheets = workbook.getNumberOfSheets();

         for(int i = 0; i < numberOfSheets; ++i) {
            Sheet sheet = workbook.getSheetAt(i);
            if (sheet != null) {
               map = readExcelSheet(i, sheet, map);
            }
         }

         return map;
      } else {
         return map;
      }
   }

   public static String readExcelContent(String filepath) throws EncryptedDocumentException, InvalidFormatException, IOException {
      Workbook workbook = getWorkbook(filepath);
      StringBuffer sb = new StringBuffer();
      if (workbook != null) {
         int numberOfSheets = workbook.getNumberOfSheets();
         Sheet sheet = workbook.getSheetAt(0);
         if (sheet == null) {
            return sb.toString();
         }

         int rowNos = sheet.getLastRowNum() + 1;
         if (rowNos > 5) {
            rowNos = 5;
         }

         for(int i = 0; i < rowNos; ++i) {
            Row row = sheet.getRow(i);
            if (row != null) {
               int columNos = row.getLastCellNum();

               for(int j = 0; j < columNos; ++j) {
                  sb.append(row.getCell(j).toString() + " ");
               }
            }

            sb.append("^||^");
         }
      }

      return sb.toString();
   }

   private static Workbook getWorkbook(String filepath) throws EncryptedDocumentException, InvalidFormatException, IOException {
      FileInputStream is = null;
      Workbook wb = null;
      if (StringUtils.isBlank(filepath)) {
         throw new IllegalArgumentException("文件路径不能为空");
      } else {
         String suffiex = getSuffiex(filepath);
         if (StringUtils.isBlank(suffiex)) {
            throw new IllegalArgumentException("文件后缀不能为空");
         } else if (!"xls".equals(suffiex) && !"xlsx".equals(suffiex)) {
            throw new IllegalArgumentException("该文件非Excel文件");
         } else {
            try {
               is = new FileInputStream(filepath);
               if ("xls".equals(suffiex)) {
                  wb = new HSSFWorkbook(is);
               } else if ("xlsx".equals(suffiex)) {
                  wb = new XSSFWorkbook(is);
               }
            } finally {
               if (is != null) {
                  is.close();
               }

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

            }

            return wb;
         }
      }
   }

   private static Map<String, List<String>> readExcelSheet(int sheetnum, Sheet sheet, Map<String, List<String>> map) {
      if (sheet != null) {
         int rowNos = sheet.getLastRowNum() + 1;

         for(int i = 0; i <= rowNos; ++i) {
            Row row = sheet.getRow(i);
            if (row != null) {
               int columNos = row.getLastCellNum();

               for(int j = 0; j < columNos; ++j) {
                  if (map.containsKey(sheetnum + "_" + j)) {
                     ((List)map.get(sheetnum + "_" + j)).add(row.getCell(j) == null ? "" : row.getCell(j).toString());
                  } else {
                     List<String> l = new ArrayList();
                     l.add(row.getCell(j) == null ? "" : row.getCell(j).toString());
                     map.put(sheetnum + "_" + j, l);
                  }
               }
            }
         }
      }

      return map;
   }

   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 Map<String, List<String>> readExcelFTP(FTPClient ftp, String absolution, String filename, String fileurl) throws EncryptedDocumentException, InvalidFormatException, IOException {
      Workbook workbook = getWorkbookFTP(ftp, absolution, filename, fileurl);
      Map<String, List<String>> map = new HashMap();
      if (workbook != null) {
         int numberOfSheets = workbook.getNumberOfSheets();

         for(int i = 0; i < numberOfSheets; ++i) {
            Sheet sheet = workbook.getSheetAt(i);
            if (sheet != null) {
               map = readExcelSheet(i, sheet, map);
            }
         }

         return map;
      } else {
         return map;
      }
   }

   private static Workbook getWorkbookFTP(FTPClient ftp, String filepath, String filename, String fileurl) throws EncryptedDocumentException, InvalidFormatException, IOException {
      Workbook wb = null;
      if (StringUtils.isBlank(filepath)) {
         throw new IllegalArgumentException("文件路径不能为空");
      } else {
         String suffiex = getSuffiex(filepath);
         if (StringUtils.isBlank(suffiex)) {
            throw new IllegalArgumentException("文件后缀不能为空");
         } else {
            InputStream inputstream = null;
            if (!"xls".equals(suffiex) && !"xlsx".equals(suffiex)) {
               throw new IllegalArgumentException("该文件非Excel文件");
            } else {
               try {
                  ftp.changeWorkingDirectory(fileurl);
                  ftp.enterLocalPassiveMode();
                  inputstream = ftp.retrieveFileStream(filename);
                  if (inputstream != null) {
                     if ("xls".equals(suffiex)) {
                        POIFSFileSystem pf = new POIFSFileSystem(inputstream);
                        wb = new HSSFWorkbook(pf);
                     } else if ("xlsx".equals(suffiex)) {
                        OPCPackage opc = OPCPackage.open(inputstream);
                        wb = new XSSFWorkbook(opc);
                     }
                  }
               } finally {
                  if (inputstream != null) {
                     inputstream.close();
                     ftp.completePendingCommand();
                  }

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

               }

               return wb;
            }
         }
      }
   }

   public static Map<String, List<String>> readExcelSFTP(SFTPUtil sftp, String filepath) throws Exception {
      Workbook workbook = getWorkbookSFTP(sftp, filepath);
      Map<String, List<String>> map = new HashMap();
      if (workbook != null) {
         int numberOfSheets = workbook.getNumberOfSheets();

         for(int i = 0; i < numberOfSheets; ++i) {
            Sheet sheet = workbook.getSheetAt(i);
            if (sheet != null) {
               map = readExcelSheet(i, sheet, map);
            }
         }

         return map;
      } else {
         return map;
      }
   }

   public static String readExcelContentFTP(FTPClient ftp, String absolution, String filename, String fileurl) throws EncryptedDocumentException, InvalidFormatException, IOException {
      Workbook workbook = getWorkbookFTP(ftp, absolution, filename, fileurl);
      StringBuffer sb = new StringBuffer();
      if (workbook != null) {
         int numberOfSheets = workbook.getNumberOfSheets();
         Sheet sheet = workbook.getSheetAt(0);
         if (sheet == null) {
            return sb.toString();
         }

         int rowNos = sheet.getLastRowNum() + 1;
         if (rowNos > 5) {
            rowNos = 5;
         }

         for(int i = 0; i < rowNos; ++i) {
            Row row = sheet.getRow(i);
            if (row != null) {
               int columNos = row.getLastCellNum();

               for(int j = 0; j < columNos; ++j) {
                  sb.append(row.getCell(j).toString() + " ");
               }
            }

            sb.append("^||^");
         }
      }

      return sb.toString();
   }

   public static String readExcelContentSFTP(SFTPUtil sftp, String filepath) throws Exception {
      Workbook workbook = getWorkbookSFTP(sftp, filepath);
      StringBuffer sb = new StringBuffer();
      if (workbook != null) {
         int numberOfSheets = workbook.getNumberOfSheets();
         Sheet sheet = workbook.getSheetAt(0);
         if (sheet == null) {
            return sb.toString();
         }

         int rowNos = sheet.getLastRowNum() + 1;
         if (rowNos > 5) {
            rowNos = 5;
         }

         for(int i = 0; i <= rowNos; ++i) {
            Row row = sheet.getRow(i);
            if (row != null) {
               int columNos = row.getLastCellNum();

               for(int j = 0; j < columNos; ++j) {
                  sb.append(row.getCell(j).toString() + " ");
               }
            }

            sb.append("^||^");
         }
      }

      return sb.toString();
   }

   private static Workbook getWorkbookSFTP(SFTPUtil sftp, String filepath) throws Exception {
      Workbook wb = null;
      if (StringUtils.isBlank(filepath)) {
         throw new IllegalArgumentException("文件路径不能为空");
      } else {
         String suffiex = getSuffiex(filepath);
         if (StringUtils.isBlank(suffiex)) {
            throw new IllegalArgumentException("文件后缀不能为空");
         } else {
            InputStream inputstream = null;
            if (!"xls".equals(suffiex) && !"xlsx".equals(suffiex)) {
               throw new IllegalArgumentException("该文件非Excel文件");
            } else {
               try {
                  inputstream = sftp.getDataInputStream(filepath);
                  if ("xls".equals(suffiex)) {
                     POIFSFileSystem pf = new POIFSFileSystem(inputstream);
                     wb = new HSSFWorkbook(pf);
                  } else if ("xlsx".equals(suffiex)) {
                     OPCPackage opc = OPCPackage.open(inputstream);
                     wb = new XSSFWorkbook(opc);
                  }
               } finally {
                  if (inputstream != null) {
                     inputstream.close();
                  }

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

               }

               return wb;
            }
         }
      }
   }

   public static void main(String[] args) {
      String path = "D:\\lixin\\R_1578386000651.xlsx";

      try {
         System.out.println(readExcel(path));
      } catch (Exception e) {
         e.printStackTrace();
      }

   }
}
