package cn.exploring.engine.server.admin.util;

import org.apache.poi.hssf.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;



public class ExcelHelper {

	public static void xlsxExcel2007(List<?> xlsx,HttpServletResponse response){
		if(xlsx != null && xlsx.size()==0){
			return;
		}
		  // 创建Excel文档
//		  XSSFWorkbook hwb = new XSSFWorkbook();
		HSSFWorkbook hwb = new HSSFWorkbook();
		  //通过反射，获取对象的字段
		  Field[] fields = xlsx.get(0).getClass().getDeclaredFields();
		  String[] names = new String[fields.length];
		  for(int i = 0;i<fields.length;i++){
			  names[i]=fields[i].getName();
		  }
		  // sheet 对应一个工作页
		  HSSFSheet sheet = hwb.createSheet("pldrxkxxmb");

		  sheet.setDefaultColumnWidth(21);//设置单元格宽度

		  HSSFRow firstrow = sheet.createRow(0); // 下标为0的行开始
		  HSSFCell[] firstcell = new HSSFCell[fields.length];
		  for (int j = 0; j < fields.length; j++) {
			  firstcell[j] = firstrow.createCell(j);
			  firstcell[j].setCellValue(new HSSFRichTextString(names[j]));
		  }
		  for (int i = 0; i < xlsx.size(); i++) {
			  // 创建一行
			  HSSFRow row = sheet.createRow(i + 1);
			  // 得到要插入的每一条记录
			  Object obj = xlsx.get(i);
			  Field[] field = obj.getClass().getDeclaredFields();
			  for (int j = 0; j < field.length; j++) {
				  String name = field[j].getName();
				  String type = field[j].getGenericType().toString();
				  if("int".equals(type)){
					  type = "class java.lang.Integer";
				  }
				  if("short".equals(type)){
					  type = "class java.lang.Short";
				  }
				  if("double".equals(type)){
					  type = "class java.lang.Double";
				  }
				  if("long".equals(type)){
					  type = "class java.lang.Long";
				  }
				  field[j].setAccessible(true);
				 // System.out.println("=========="+name);
				  String n = name.substring(0, 1).toUpperCase();
				  name = n+name.substring(1);
				//  System.out.println("=========="+name);
				  // 在一行内循环
				  try {
					  Method m;
					  if(type.equals("class java.lang.String")){
//						 m = ReflectionUtils.getDeclaredMethod(obj, "get"+name, null);
						 m = obj.getClass().getDeclaredMethod("get"+name);
						 m.setAccessible(true);
						 String value = (String)m.invoke(obj);
						 System.out.println("get"+name+"---"+value);
						 HSSFCell fd = row.createCell(j);
						 if(value != null){
							 fd.setCellValue(value);
						 }
					  }
					  if(type.equals("class java.lang.Long")){
						  m = obj.getClass().getDeclaredMethod("get"+name);
						  m.setAccessible(true);
						  Long value = (Long)m.invoke(obj);
						 // System.out.println("get"+name+"---"+value);
						  HSSFCell fd = row.createCell(j);
						  if(value != null){
							  fd.setCellValue(value);
						  }
					  }
					  if(type.equals("class java.lang.Integer")){
						 m = obj.getClass().getDeclaredMethod("get"+name);
						 m.setAccessible(true);
						 Integer value = (Integer)m.invoke(obj);
						// System.out.println("get"+name+"---"+value);
						 HSSFCell fd = row.createCell(j);
						 if(value != null){
							 fd.setCellValue(value);
						 }
					  }
					  if (type.equals("class java.lang.Short"))
			          {
			                m = obj.getClass().getDeclaredMethod("get" + name);
			                m.setAccessible(true);
			                Short value = (Short) m.invoke(obj);
			               // System.out.println("get"+name+"---"+value);
			                HSSFCell fd = row.createCell(j);
			                if(value != null){
			                	fd.setCellValue(value);
			                }
			          }
		            if (type.equals("class java.lang.Double"))
		            {
		                m = obj.getClass().getDeclaredMethod("get" + name);
		                m.setAccessible(true);
		                Double value = (Double) m.invoke(obj);
		               // System.out.println("get"+name+"---"+value);
		                HSSFCell fd = row.createCell(j);
		                if(value != null){
		                	fd.setCellValue(value);
		                }
		            }
		            if (type.equals("class java.lang.Boolean"))
		            {
		                m = obj.getClass().getDeclaredMethod("get" + name);
		                m.setAccessible(true);
		                Boolean value = (Boolean) m.invoke(obj);
		                //System.out.println("get"+name+"---"+value);
		                HSSFCell fd = row.createCell(j);
						fd.setCellValue(value);
		            }
		            if (type.equals("class java.util.Date"))
		            {
		                m = obj.getClass().getDeclaredMethod("get" + name);
		                m.setAccessible(true);
		                Date value = (Date) m.invoke(obj);
		               // System.out.println("get"+name+"---"+TimeUtil.date2String(value,TimeUtil.OTHER_PATTERN));
		                HSSFCell fd = row.createCell(j);
		                if(value != null){
		                	fd.setCellValue(TimeUtil.date2String(value,TimeUtil.OTHER_PATTERN));
		                }
		            }
		          //  System.out.println(" ------ ------ ----- ");
				  } catch (Exception e) {
						System.out.println("抛异常："+name);
					 e.printStackTrace();
				  }
			  }
		  }
		  // 创建文件输出流，准备输出电子表格
	//      OutputStream out = new FileOutputStream("D:/pldrxkxxmb.xls");
	//      hwb.write(out);
	//      out.close();
		try {
		  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		  String now = format.format(new Date());
		  //xlsx.get(0).getClass().getSimpleName()+"_"+
		  String exportFileName = new Date().getTime()+".xls";//导出文件名
		  // 表示以附件的形式把文件发送到客户端
		  response.setHeader("Content-Disposition", "attachment;filename=" + new String((exportFileName).getBytes(), StandardCharsets.ISO_8859_1));//设定输出文件头
		  response.setContentType("application/vnd.ms-excel;charset=UTF-8");// 定义输出类型
		  // 通过response的输出流把工作薄的流发送浏览器形成文件
		  OutputStream outStream;
			outStream = response.getOutputStream();
			hwb.write(outStream);
			outStream.flush();
			outStream.close();
			hwb.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("数据库导出成功");
	}
}
