package com.yifu.cloud.plus.v1.yifu.social.util;

import com.aspose.cells.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.nio.file.Files;


// DEMO,实际应用见：ExcelToImage
public class NewExcelToImage {
	private static final String OUTPUT_DIR = "output";
	private static final String IMAGE_FILE = OUTPUT_DIR + File.separator + "WorksheetToImage.png";

	public static void main(String[] args) {
		try {
			new File(OUTPUT_DIR).mkdirs();
			createWorksheetImage();
			System.out.println("\n=== 转换完成!图片已保存到 output 目录 ===");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void createWorksheetImage() {
		System.out.println("1.创建工作表并转换为图片...");

		// 使用 try-with-resources 自动管理临时文件
		File tempExcelFile = null;

		try (XSSFWorkbook workbook = new XSSFWorkbook()) {
			// 1. 创建临时文件（自动删除）
			tempExcelFile = File.createTempFile("excel_temp_", ".xlsx");
			tempExcelFile.deleteOnExit(); // JVM退出时自动删除

			// 2. 构建Excel内容
			XSSFSheet worksheet = workbook.createSheet("sales Report");

			// 标题行
			XSSFRow titleRow = worksheet.createRow(0);
			XSSFCell titleCell = titleRow.createCell(0);
			titleCell.setCellValue("sales Report");

			// 表头行
			XSSFRow headerRow = worksheet.createRow(2);
			String[] headers = {"Date", "Product", "Customer", "Amount", "show"};
			for (int i = 0; i < headers.length; i++) {
				XSSFCell cell = headerRow.createCell(i);
				cell.setCellValue(headers[i]);
			}

			// 数据行
			Object[][] data = {{"1", "2", "3", "4", "5"},
					{"6", "7", "8", "9", "10"},
					{"11", "12", "13", "14", "15"}};
			for (int i = 0; i < data.length; i++) {
				XSSFRow row = worksheet.createRow(i + 3);
				for (int j = 0; j < data[i].length; j++) {
					XSSFCell cell = row.createCell(j);
					cell.setCellValue(String.valueOf(data[i][j]));
				}
			}

			// 自动调整列宽
			for (int i = 0; i < 5; i++) {
				worksheet.autoSizeColumn(i);
			}

			// 3. 写入临时文件（使用 try-with-resources）
			try (FileOutputStream fos = new FileOutputStream(tempExcelFile)) {
				workbook.write(fos);
			}
			System.out.println("   √ Excel临时文件已创建：" + tempExcelFile.getAbsolutePath());

			// 4. 使用流方式读取并转换为图片（避免多次磁盘IO）
			convertExcelToImage(tempExcelFile, IMAGE_FILE);
			System.out.println("   √ 工作表图片已保存：" + IMAGE_FILE);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 5. 清理临时文件
			if (tempExcelFile != null && tempExcelFile.exists()) {
				boolean deleted = tempExcelFile.delete();
				if (deleted) {
					System.out.println("   √ 临时文件已清理：" + tempExcelFile.getName());
				}
			}
		}
	}

	/**
	 * 将Excel文件转换为图片（使用流方式）
	 */
	private static void convertExcelToImage(File excelFile, String imagePath) throws Exception {
		// 使用 try-with-resources 自动管理 Workbook 资源
		try (FileInputStream fis = new FileInputStream(excelFile);
			 ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

			// 从流加载Excel
			Workbook workbook = new Workbook(fis);
			Worksheet worksheet = workbook.getWorksheets().get(0);

			// 设置页面选项
			ImageOrPrintOptions options = new ImageOrPrintOptions();
			options.setImageType(ImageType.PNG);
			options.setOnePagePerSheet(true);
			options.setHorizontalResolution(96);  // 设置水平分辨率
			options.setVerticalResolution(96);    // 设置垂直分辨率

			// 渲染工作表
			SheetRender render = new SheetRender(worksheet, options);

			// 直接渲染到流（避免中间文件）
			render.toImage(0, imagePath);
		}
	}
}