package com.zcloud.util;

import com.zcloud.entity.PageData;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.servlet.view.document.AbstractXlsView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 说明：导出到EXCEL
 * 作者：luoxiaobao
 * 官网：www.qdkjchina.com
 */
public class ObjectExcelImgView extends AbstractXlsView {

	@Override
	protected void buildExcelDocument(Map<String, Object> model,
                                      Workbook workbook, HttpServletRequest request,
                                      HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		Date date = new Date();
		String filename = DateUtil.date2Str(date, "yyyyMMddHHmmss");
		HSSFSheet sheet;
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition", "attachment;filename="+filename+".xls");

		HSSFWorkbook book = (HSSFWorkbook) workbook;
		sheet = book.createSheet("sheet1");

		List<String> titles = (List<String>) model.get("titles");
		int len = titles.size();
		HSSFCellStyle headerStyle = book.createCellStyle(); //标题样式
		headerStyle.setAlignment(HorizontalAlignment.CENTER);
		headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
		HSSFFont headerFont = book.createFont();			//标题字体
		headerFont.setBold(true);
		headerFont.setFontHeightInPoints((short)11);
		headerStyle.setFont(headerFont);
		short height=25*20;
		HSSFRow row = sheet.createRow(0);
		for(int i=0; i<len; i++){ //设置标题
			String title = titles.get(i);
			row.setRowStyle(headerStyle);
			row.createCell(i).setCellValue(title);
		}
		sheet.getRow(0).setHeight(height);

		HSSFCellStyle contentStyle = book.createCellStyle(); //内容样式
		contentStyle.setAlignment(HorizontalAlignment.CENTER);
		List<PageData> varList = (List<PageData>) model.get("varList");
		int varCount = varList.size();
		for(int i=0; i<varCount; i++){
			PageData vpd = varList.get(i);
			HSSFRow rows = sheet.createRow(i+1);
			for(int j=0;j<len;j++){
				if(vpd.getString("var"+(j+1))!="") {
					 BufferedImage bufferImg = null;//图片一
					  ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
					  bufferImg = ImageIO.read(new File("C:/person.jpg"));
		                ImageIO.write(bufferImg, "jpg", byteArrayOut);
		                HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
		                HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 1, (short) 2, height, 2);
		                patriarch.createPicture(anchor, book.addPicture(byteArrayOut
		                        .toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
		                rows.setRowStyle(contentStyle);
						//rows.createCell(j).setCellValue(varstr);

				}else {

					String varstr = vpd.getString("var"+(j+1)) != null ? vpd.getString("var"+(j+1)) : "";
					rows.setRowStyle(contentStyle);
					rows.createCell(j).setCellValue(varstr);
				}

			}

		}

	}

	   public static void main(String[] args) {

           FileOutputStream fileOut = null;
           BufferedImage bufferImg = null;//图片一
           BufferedImage bufferImg1 = null;//图片二
           try {
               // 先把读进来的图片放到一个ByteArrayOutputStream中，以便产生ByteArray
               ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
               ByteArrayOutputStream byteArrayOut1 = new ByteArrayOutputStream();

               //将两张图片读到BufferedImage
               bufferImg = ImageIO.read(new File("C:/sm.jpg"));
               bufferImg1 = ImageIO.read(new File("C:/sm.jpg"));
               ImageIO.write(bufferImg, "jpg", byteArrayOut);
               ImageIO.write(bufferImg1, "jpg", byteArrayOut1);

               // 创建一个工作薄
               HSSFWorkbook wb = new HSSFWorkbook();
               //创建一个sheet
               HSSFSheet sheet = wb.createSheet("out put excel");

               HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
               /**
                * 该构造函数有8个参数
                * 前四个参数是控制图片在单元格的位置，分别是图片距离单元格left，top，right，bottom的像素距离
                * 后四个参数，前连个表示图片左上角所在的cellNum和 rowNum，后天个参数对应的表示图片右下角所在的cellNum和 rowNum，
                * excel中的cellNum和rowNum的index都是从0开始的
                *
                */
               //图片一导出到单元格B2中
               HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 1, (short) 2, (short) 10, 2);
               //图片二导出到单元格C3到E5中，且图片的left和top距离边框50
               HSSFClientAnchor anchor1 = new HSSFClientAnchor(50, 50, 0, 0,
                       (short) 2, 2, (short) 5, 5);

               // 插入图片
               patriarch.createPicture(anchor, wb.addPicture(byteArrayOut
                       .toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
               patriarch.createPicture(anchor1, wb.addPicture(byteArrayOut1
                       .toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));

               fileOut = new FileOutputStream("C:/output_Excel.xls");
               // 写入excel文件
               wb.write(fileOut);
           } catch (IOException io) {
               io.printStackTrace();
               System.out.println("io erorr : " + io.getMessage());
           } finally {
               if (fileOut != null) {
                   try {
                       fileOut.close();
                   } catch (IOException e) {
                       e.printStackTrace();
                   }
               }
           }
       }

}
