package com.neusoft.smart.pos.framework.utils;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
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.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;


public class ExcelUtils {
	
	private static Logger logger = LoggerFactory.getLogger(ExcelUtils.class);
	
	private static int SPLIT_COUNT = 65536;                                    //Excel每个工作表的行数
	
	// private ArrayList fieldName = null; //excel数据的抬头栏，即名称栏
	
	// private ArrayList fieldData = null; //excel导出的实际数据
	
	// private HSSFWorkbook workBook = null;//一个excel文件
	
	//有参构造器，限定了使用此类时，必须首先构建好两个list参数，并将所需数据放入上述两个list。
	//其中fieldName这个list可以使用泛型约束List<String>
	//fieldData这个可以使用泛型约束List<List<Object>>
	public static void exportExcel(List<String> fieldName, List<List<Object>> fieldData, OutputStream os) throws Exception {
		SXSSFWorkbook workBook = createXsshWorkbook(fieldName, fieldData);
		workBook.write(os);
		os.close();
	}
	
	
	public static void export07Excel(List<String> fieldName, List<List<Object>> fieldData, OutputStream os) throws Exception {
		Workbook workBook = createXsshWorkbook(fieldName, fieldData);
		workBook.write(os);
		os.close();
	}
	
	/**
	 * @return HSSFWorkbook
	 */
	public static HSSFWorkbook createWorkbook(List<String> fieldName, List<List<Object>> fieldData) {
		HSSFWorkbook workBook = new HSSFWorkbook();//创建一个工作簿
		int rows = fieldData.size();//清点出输入数据的行数
		int sheetNum = 0;//将工作表个数清零
		//根据数据的行数与每个工作表所能容纳的行数，求出需要创建工作表的个数
		if (rows == 0) {
			sheetNum = 1;
		} else if (rows % SPLIT_COUNT == 0) {
			sheetNum = rows / SPLIT_COUNT;
		} else {
			sheetNum = rows / SPLIT_COUNT + 1;
		}
		
		for (int i = 1; i <= sheetNum; i++) {
			HSSFSheet sheet = workBook.createSheet("Page " + i);//创建工作表
			
			HSSFCellStyle textStyle = workBook.createCellStyle();//创建文本单元格样式
			HSSFDataFormat format = workBook.createDataFormat();
			textStyle.setDataFormat(format.getFormat("@"));
			
			HSSFRow headRow0 = sheet.createRow(0);
			HSSFCell cell0 = headRow0.createCell(0);
			
			HSSFCellStyle style0 = workBook.createCellStyle();
			HSSFFont font0 = workBook.createFont();
			font0.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
			short color0 = HSSFColor.RED.index;
			font0.setColor(color0);
			style0.setFont(font0);
			cell0.setCellStyle(style0);
			cell0.setCellValue("导入模板");
			
			HSSFRow headRow = sheet.createRow(1); //创建第一栏，抬头栏
			for (int j = 0; j < fieldName.size(); j++) {
				sheet.setDefaultColumnStyle(j, textStyle);//设置单元格格式默认为文本
				HSSFCell cell = headRow.createCell(j);//创建抬头栏单元格
				//设置单元格格式
				cell.setCellType(HSSFCell.CELL_TYPE_STRING);
				sheet.setColumnWidth(j, 6000);
				HSSFCellStyle style = workBook.createCellStyle();
				HSSFFont font = workBook.createFont();
				font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
				short color = HSSFColor.RED.index;
				font.setColor(color);
				style.setFont(font);
				//将数据填入单元格
				if (fieldName.get(j) != null) {
					cell.setCellStyle(style);
					cell.setCellValue(fieldName.get(j));
				} else {
					cell.setCellStyle(style);
					cell.setCellValue("-");
				}
			}
			//创建数据栏单元格并填入数据
			for (int k = 0; k < (rows < SPLIT_COUNT ? rows : SPLIT_COUNT); k++) {
				if (((i - 1) * SPLIT_COUNT + k) >= rows)
					break;
				HSSFRow row = sheet.createRow(k + 2);
				ArrayList rowList = (ArrayList) fieldData.get((i - 1) * SPLIT_COUNT + k);
				for (int n = 0; n < rowList.size(); n++) {
					HSSFCell cell = row.createCell(n);
					if (rowList.get(n) != null) {
						cell.setCellValue(rowList.get(n).toString());
					} else {
						cell.setCellValue("");
					}
				}
			}
		}
		return workBook;
	}
	
	/**
	 * @return HSSFWorkbook
	 */
	public static SXSSFWorkbook createXsshWorkbook(List<String> fieldName, List<List<Object>> fieldData) {
		SXSSFWorkbook workBook = new SXSSFWorkbook();//创建一个工作簿
		int rows = fieldData.size();//清点出输入数据的行数
		int sheetNum = 0;//将工作表个数清零
		//根据数据的行数与每个工作表所能容纳的行数，求出需要创建工作表的个数
		if (rows == 0) {
			sheetNum = 1;
		} else if (rows % SPLIT_COUNT == 0) {
			sheetNum = rows / SPLIT_COUNT;
		} else {
			sheetNum = rows / SPLIT_COUNT + 1;
		}
		
		for (int i = 1; i <= sheetNum; i++) {
			Sheet sheet = workBook.createSheet("Page " + i);//创建工作表
			Row headRow = sheet.createRow(0); //创建第一栏，抬头栏
			for (int j = 0; j < fieldName.size(); j++) {
				Cell cell = headRow.createCell(j);//创建抬头栏单元格
				//设置单元格格式
				cell.setCellType(HSSFCell.CELL_TYPE_STRING);
				sheet.setColumnWidth(j, 6000);
				CellStyle style = workBook.createCellStyle();
				Font font = workBook.createFont();
				font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
				short color = HSSFColor.RED.index;
				font.setColor(color);
				style.setFont(font);
				//将数据填入单元格
				if (fieldName.get(j) != null) {
					cell.setCellStyle(style);
					cell.setCellValue((String) fieldName.get(j));
				} else {
					cell.setCellStyle(style);
					cell.setCellValue("-");
				}
			}
			//创建数据栏单元格并填入数据
			for (int k = 0; k < (rows < SPLIT_COUNT ? rows : SPLIT_COUNT); k++) {
				if (((i - 1) * SPLIT_COUNT + k) >= rows)
					break;
				Row row = sheet.createRow(k + 1);
				ArrayList rowList = (ArrayList) fieldData.get((i - 1) * SPLIT_COUNT + k);
				for (int n = 0; n < rowList.size(); n++) {
					Cell cell = row.createCell(n);
					if (rowList.get(n) != null) {
						cell.setCellValue((String) rowList.get(n).toString());
					} else {
						cell.setCellValue("");
					}
				}
			}
		}
		return workBook;
	}
	
	/**
	 * 功能描述: 创建多个sheet的我rkbook<br>
	 * 〈功能详细描述〉
	 *
	 * @param fieldName
	 * @param fieldData
	 * @param workBook
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	public static HSSFWorkbook createWorkbookWithMultiSheets(List<Object> fieldName, String sheetName,
			List<List<Object>> fieldData, HSSFWorkbook workBook) {
		if (workBook == null) {
			workBook = new HSSFWorkbook();//创建一个工作簿
		}
		int rows = fieldData.size();//清点出输入数据的行数
		int sheetNum = 0;//将工作表个数清零
		//根据数据的行数与每个工作表所能容纳的行数，求出需要创建工作表的个数
		if (rows == 0) {
			sheetNum = 1;
		} else if (rows % SPLIT_COUNT == 0) {
			sheetNum = rows / SPLIT_COUNT;
		} else {
			sheetNum = rows / SPLIT_COUNT + 1;
		}
		
		for (int i = 1; i <= sheetNum; i++) {
			HSSFSheet sheet = null;
			if (sheetNum == 1) {
				sheet = workBook.createSheet(sheetName);//创建工作表
			} else {
				sheet = workBook.createSheet(sheetName + i);//创建工作表
			}
			HSSFRow headRow = sheet.createRow(0); //创建第一栏，抬头栏
			for (int j = 0; j < fieldName.size(); j++) {
				HSSFCell cell = headRow.createCell(j);//创建抬头栏单元格
				//设置单元格格式
				cell.setCellType(HSSFCell.CELL_TYPE_STRING);
				sheet.setColumnWidth(j, 6000);
				HSSFCellStyle style = workBook.createCellStyle();
				HSSFFont font = workBook.createFont();
				font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
				short color = HSSFColor.RED.index;
				font.setColor(color);
				style.setFont(font);
				//将数据填入单元格
				if (fieldName.get(j) != null) {
					cell.setCellStyle(style);
					cell.setCellValue((String) fieldName.get(j));
				} else {
					cell.setCellStyle(style);
					cell.setCellValue("-");
				}
			}
			//创建数据栏单元格并填入数据
			for (int k = 0; k < (rows < SPLIT_COUNT ? rows : SPLIT_COUNT); k++) {
				if (((i - 1) * SPLIT_COUNT + k) >= rows)
					break;
				HSSFRow row = sheet.createRow(k + 1);
				ArrayList rowList = (ArrayList) fieldData.get((i - 1) * SPLIT_COUNT + k);
				for (int n = 0; n < rowList.size(); n++) {
					HSSFCell cell = row.createCell(n);
					if (rowList.get(n) != null) {
						cell.setCellValue((String) rowList.get(n).toString());
					} else {
						cell.setCellValue("");
					}
				}
			}
		}
		return workBook;
	}
	
	/**
	 * 功能描述:解析excel文件 <br>
	 * 〈功能详细描述〉
	 *
	 * @param file
	 * @return 返回excel中每行值得列表
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	public static List<String[]> parseFile(MultipartFile file) throws Exception {
		List<String[]> list = new ArrayList<>();
		try {
			//新建WorkBook
			Workbook wb = WorkbookFactory.create(file.getInputStream());
			//获取Sheet（工作薄）总个数
			int sheetNumber = wb.getNumberOfSheets();
			for (int i = 0; i < sheetNumber; i++) {
				//获取Sheet（工作薄）
				Sheet sheet = wb.getSheetAt(i);
				//开始行数
				int firstRow = sheet.getFirstRowNum();
				//结束行数
				int lastRow = sheet.getLastRowNum();
				//判断该Sheet（工作薄)是否为空
				boolean isEmpty = false;
				if (firstRow == lastRow) {
					isEmpty = true;
				}
				if (!isEmpty) {
					for (int j = firstRow + 1; j <= lastRow; j++) {
						//获取一行
						Row row = sheet.getRow(j);
						if (row != null) {
							//开始列数
							int firstCell = row.getFirstCellNum();
							//结束列数
							int lastCell = row.getLastCellNum();
							if (lastCell != -1) {
								//判断该行是否为空
								String[] value = new String[lastCell];
								if (firstCell != lastCell) {
									for (int k = firstCell; k < lastCell; k++) {
										//获取一个单元格
										Cell cell = row.getCell(k);
										if (cell == null) {
											continue;
										}
										cell.setCellType(Cell.CELL_TYPE_STRING);
										Object str = null;
										//获取单元格，值的类型
										int cellType = cell.getCellType();
										
										if (cellType == Cell.CELL_TYPE_NUMERIC) {
											str = cell.getNumericCellValue();
										} else if (cellType == 1) {
											str = cell.getStringCellValue();
										} else if (cellType == 2) {
										} else if (cellType == 4) {
											str = cell.getBooleanCellValue();
										}
										value[k] = str.toString();
									}
								}
								//每一行循环完对应的就是一个用户故事的所有属性全部拿到
								list.add(value);
							}
						}
					}
				}
			}
			wb.close();
		} catch (Exception e) {
			logger.error("Excel解析失败!", e.getMessage(), e);
			throw e;
		}
		
		List<String[]> emptyRows = new ArrayList<>();
		for (String[] row : list) {
			boolean isEmpty = true;
			for (String cell : row) {
				if (!StringUtils.isEmpty(cell)) {
					isEmpty = false;
					break;
				}
			}
			if (isEmpty) {
				emptyRows.add(row);
			}
		}
		list.removeAll(emptyRows);
		return list;
	}
	
	
}
