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.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;

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

	@Override
	protected void buildExcelDocument(Map<String, Object> model,
                                      Workbook workbook, HttpServletRequest request,
                                      HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		String beji = Const.HTTPFILEURL;
		//beji =beji.replaceAll("\\\\", "/");

		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);
		if(len>250) {
			len = 250;
		}
		for(int i=0; i<len; i++){ //设置标题
			String title = titles.get(i);
			row.setRowStyle(headerStyle);
			if(title.length()>250) {
				row.createCell(i).setCellValue(title.substring(0, 250));
			}else {
				row.createCell(i).setCellValue(title);
			}
		}
		sheet.getRow(0).setHeight(height);

		HSSFCellStyle contentStyle = book.createCellStyle(); //内容样式
		HSSFPatriarch patriarch = sheet.createDrawingPatriarch();

		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++){
				String valKey = "var"+(j+1);
				String imgKey = "img" +(j+1);
				if(vpd.containsKey(valKey)) {
					String varstr = vpd.getString(valKey) != null ? vpd.getString("var"+(j+1)) : "";
					rows.setRowStyle(contentStyle);
					rows.createCell(j).setCellValue(varstr);
				}
				if(vpd.containsKey(imgKey)) {
					String varstr = vpd.getString(imgKey) != null ? vpd.getString("img"+(j+1)) : "";
					if(Tools.isEmpty(varstr)) {
						continue;
					}
					try {
						URL url = new URL(beji + varstr);
						HttpURLConnection conn = (HttpURLConnection)url.openConnection();
						conn.setRequestMethod("GET");
						conn.setConnectTimeout(5 * 1000);
						InputStream inStream = conn.getInputStream();
						byte[] data = readInputStream(inStream);

						HSSFClientAnchor anchor1 = new HSSFClientAnchor(0, 0, 0, 0,(short) (j), (i+1), (short) (j+1), (i+2));
						patriarch.createPicture(anchor1, book.addPicture(data, HSSFWorkbook.PICTURE_TYPE_JPEG));
					}catch (Exception e) {
						System.out.println("未找到图片");
						e.printStackTrace();
					}
//					BufferedImage bufferImg = null;//图片一
//					ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();//
//					File file=new File(beji+varstr);
//					if(file.exists()) {//https://wwag.qhdsafety.com/file//uploadFiles/yhtp/07bd077457ec4da7bd6ec2219984079c/20220126/545463a3effe4a3d9d50dc701c69cc01.png
//						bufferImg = ImageIO.read(file);
//						ImageIO.write(bufferImg, "jpg", byteArrayOut);
//						 HSSFClientAnchor anchor1 = new HSSFClientAnchor(0, 0, 0, 0,(short) (j), (i+1), (short) (j+1), (i+2));
//						   patriarch.createPicture(anchor1, book.addPicture(byteArrayOut
//			                       .toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
//					}

				}

			}

		}

	}

	private static byte[] readInputStream(InputStream inStream) throws Exception{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		//创建一个Buffer字符串
		byte[] buffer = new byte[1024];
		//每次读取的字符串长度，如果为-1，代表全部读取完毕
		int len = 0;
		//使用一个输入流从buffer里把数据读取出来
		while( (len=inStream.read(buffer)) != -1 ){
			//用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
			outStream.write(buffer, 0, len);
		}
		//关闭输入流
		inStream.close();
		//把outStream里的数据写入内存
		return outStream.toByteArray();
	}



}
