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


import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.OSSUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.social.config.SocialFriendConfig;
import com.yifu.cloud.plus.v1.yifu.social.entity.TSocialFriendBackLog;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.util.Base64;

/**
 * @Author fxj
 * @Date 2024/12/9
 * @Description  excel 转换为 图片 并上传阿里云 （上传后自动删除生成的图片文件）
 * @Version 1.0
 */
@Component
public class ExcelToImage {

	private final static String  toImag ="\\ToImg.png";

	private static final String  TO_IMAGE_TEMP ="\\ToImgTemp.png";

	private final static String  toImagParamError = "：带印章excel生成图片传参异常";

	private final static String  toImagConvertError = ":ExcelToImage转换异常-";

	private final static String  toImagOSSError = ":ExcelToImage上传OSS异常";

	public R<String> excelToImg(InputStream inputStream , SocialFriendConfig socialFriendConfig
			, RestTemplate restTemplate, TSocialFriendBackLog backLog){
		backLog.setLogInfo("开始转换excel为图片");
		if (null == inputStream || null == socialFriendConfig){
			return R.failed(CommonConstants.RESULT_DATA_FAIL+toImagParamError);
		}
		String projectRoot = System.getProperty(CommonConstants.USER_DIR);
		//加载Excel工作表
		Workbook wb = new Workbook();
		wb.loadFromHtml(inputStream);
		//获取工作表
		Worksheet sheet = wb.getWorksheets().get(0);
		//调用方法将Excel工作表保存为图片

		sheet.saveToImage(projectRoot+toImag);
		File file = null;
		try {
			// 上传税友文件服务器，返回文件路径
			file = new File(projectRoot+toImag);
			if (file.exists()){
				// file 压缩到1M以内
				backLog.setLogInfo("压缩大小前");
				file = compressImage(file, projectRoot);
				backLog.setLogInfo("压缩大小后");
				String key  = System.currentTimeMillis() + file.getName();
				byte[] fileContent = Files.readAllBytes(file.toPath());
				String base64String = Base64.getEncoder().encodeToString(fileContent);
				backLog.setLogInfo("转化为base64String");
				String url = socialFriendConfig.uploadPng(restTemplate, key, base64String, backLog);
				if (Common.isEmpty(url)){
					return R.failed(CommonConstants.RESULT_DATA_FAIL+toImagOSSError);
				}
				return R.ok(url);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed(CommonConstants.RESULT_DATA_FAIL+toImagConvertError+e.getMessage());
		} finally {
			if (file.exists()){
				file.delete();
			}
			if (null != inputStream){
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return R.failed(CommonConstants.RESULT_DATA_FAIL);
	}
	//压缩文件到指定大小
	private File compressImage(File originalFile, String projectRoot) throws IOException {
		BufferedImage image = ImageIO.read(originalFile);
		int quality = 100; // 从100%开始
		File compressedFile = new File(projectRoot, TO_IMAGE_TEMP);
		int maxSize = 1024 * 1024;
		while (originalFile.length() > maxSize && quality > 10) {
			quality -= 5;
			ImageIO.write(image, "png", compressedFile);
			if (compressedFile.length() < maxSize) {
				originalFile.delete();
				compressedFile.renameTo(originalFile);
				break;
			}
			compressedFile.delete();
		}
		return originalFile;
	}

	public R<URL> excelToImg(InputStream inputStream ,OSSUtil ossUtil){
		if (null == inputStream || null == ossUtil){
			return R.failed(CommonConstants.RESULT_DATA_FAIL+toImagParamError);
		}
		String projectRoot = System.getProperty(CommonConstants.USER_DIR);
		//加载Excel工作表
		Workbook wb = new Workbook();
		wb.loadFromHtml(inputStream);
		//获取工作表
		Worksheet sheet = wb.getWorksheets().get(0);
		//调用方法将Excel工作表保存为图片
		sheet.saveToImage(projectRoot+toImag);
		File file = null;
		try {
			file = new File(projectRoot+toImag);
			if (file.exists()){
				String key  = System.currentTimeMillis() + file.getName();
				if (ossUtil.uploadFileByFile(file,key,null)){
					return R.ok(ossUtil.getObjectUrl(null,key));
				}else {
					return R.failed(CommonConstants.RESULT_DATA_FAIL+toImagOSSError);
				}
			}
		} catch (Exception e) {
			return R.failed(CommonConstants.RESULT_DATA_FAIL+toImagConvertError+e.getMessage());
		} finally {
			if (file.exists()){
				file.delete();
			}
			if (null != inputStream){
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return R.failed(CommonConstants.RESULT_DATA_FAIL);
		//调用方法，将指定Excel单元格数据范围保存为图片
		//sheet.saveToImage("ToImg2.png",8,1,30,7);

		/*//调用方法将Excel保存为HTML
		sheet.saveToHtml("ToHtml.html");

		//调用方法将Excel保存为XPS
		sheet.saveToFile("ToXPS.xps", String.valueOf(FileFormat.XPS));

		//调用方法将Excel保存为CSV
		sheet.saveToFile("ToCSV.csv", String.valueOf(FileFormat.CSV));

		//调用方法将Excel保存为XML
		sheet.saveToFile("ToXML.xml", String.valueOf(FileFormat.XML));

		//调用方法将Excel保存为PostScript
		sheet.saveToFile("ToPostScript.postscript", String.valueOf(FileFormat.PostScript));

		//调用方法将Excel保存为PCL
		sheet.saveToFile("ToPCL.pcl", String.valueOf(FileFormat.PCL));*/
	}

}
