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 com.yifu.cloud.plus.v1.yifu.social.service.TSocialFriendBackLogService;
import com.yifu.cloud.plus.v1.yifu.social.vo.SociaFriendYgsAddVo;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.time.LocalDateTime;
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(String socialId, OSSUtil ossUtil, TSocialFriendBackLogService tSocialFriendBackLogService
			,InputStream inputStream , SocialFriendConfig socialFriendConfig
			, RestTemplate restTemplate, TSocialFriendBackLog backLog, InputStream zhangStream){
		backLog.setLogInfo("开始转换excel为图片");
		if (null == inputStream || null == socialFriendConfig){
			return R.failed(CommonConstants.RESULT_DATA_FAIL+toImagParamError);
		}
		String projectRoot = System.getProperty(CommonConstants.USER_DIR);
		File tempFile = null;
		File compressedTempFile = null;
		//加载Excel工作表
		Workbook wb = new Workbook();
		try {

			wb.loadFromHtml(inputStream);
			//获取工作表
			Worksheet sheet = wb.getWorksheets().get(0);
			String toImagePath = projectRoot + toImag;
			sheet.saveToImage(toImagePath);

			tempFile = new File(toImagePath);
			// 上传税友文件服务器，返回文件路径
			if (tempFile.exists()){
				// file 压缩到1M以内
				backLog.setLogInfo("压缩大小前");
				// 压缩并加章
				tempFile = compressImage(tempFile, projectRoot, zhangStream, compressedTempFile);
				backLog.setLogInfo("压缩大小后");
				String key  = System.currentTimeMillis() + tempFile.getName();
				byte[] fileContent = Files.readAllBytes(tempFile.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);
				}
				// 上传花名册到阿里云
				this.uploadHuaMingCeToOss(ossUtil, tSocialFriendBackLogService, socialId, tempFile.getName(), tempFile);
				return R.ok(url);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed(CommonConstants.RESULT_DATA_FAIL+toImagConvertError+e.getMessage());
		} finally {
			if (wb != null) {
				wb.dispose();  // 重要：释放资源并删除临时文件
			}
			if (tempFile != null && tempFile.exists()){
				tempFile.delete();
			}
			if (compressedTempFile != null && compressedTempFile.exists()){
				compressedTempFile.delete();
			}
			if (null != inputStream){
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return R.failed(CommonConstants.RESULT_DATA_FAIL);
	}

	/**
	 * @param socialId
	 * @param fileName
	 * @param file
	 * @Description: 上传花名册到阿里云
	 * @Author: hgw
	 * @Date: 2025/9/12 14:18
	 * @return: void
	 **/
	private void uploadHuaMingCeToOss(OSSUtil ossUtil, TSocialFriendBackLogService tSocialFriendBackLogService
			, String socialId, String fileName, File file) {
		try {
			String key = "socialFriend/" + socialId + "/" + System.currentTimeMillis() + fileName;
			ossUtil.uploadFileByFile(file, key, null);
			TSocialFriendBackLog backLogFile = new TSocialFriendBackLog();
			backLogFile.setSocialId(socialId);
			backLogFile.setType(19);
			backLogFile.setCreateTime(LocalDateTime.now());
			if (Common.isNotNull(key)) {
				URL fileUrl = ossUtil.getObjectUrl(null, key);
				if (Common.isNotNull(fileUrl)) {
					key += fileUrl.toString();
				}
			}
			backLogFile.setLogInfo(key);
			tSocialFriendBackLogService.save(backLogFile);
		} catch (Exception e) {
			// log.info("花名册上传到阿里云失败，查看文件使用，没有找税友要也行")
		}
	}

	//压缩文件到指定大小
	private File compressImage(File originalFile, String projectRoot, InputStream zhangStream, File compressedTempFile) throws IOException {
		BufferedImage image = ImageIO.read(originalFile);
		// 新: 加盖公章
		BufferedImage sealedImage = addSealToImage(image, zhangStream);
		ImageIO.write(sealedImage, "png", originalFile);
		int quality = 100; // 从100%开始
		int maxSize = 1024 * 1024;
		try {
			while (originalFile.length() > maxSize && quality > 10) {
				quality -= 5;
				ImageIO.write(sealedImage, "png", compressedTempFile);
				if (compressedTempFile.length() < maxSize) {
					originalFile.delete();
					compressedTempFile.renameTo(originalFile);
					break;
				}
				compressedTempFile.delete();
			}
		} catch (Exception e) {
			throw e;
		}
		return originalFile;
	}

	private BufferedImage addSealToImage(BufferedImage image, InputStream sealImagePath) throws IOException {
		BufferedImage seal = ImageIO.read(sealImagePath);

		// 设置公章目标大小
		int targetWidth = 200;  // 宽度
		int targetHeight = 200; // 高度

		// 创建缩放后的公章图像
		if (seal == null) {
			return image;
		}
		Image scaledSeal = seal.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);
		BufferedImage resizedSeal = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_ARGB);
		Graphics2D g2d = resizedSeal.createGraphics();
		g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		g2d.drawImage(scaledSeal, 0, 0, null);
		g2d.dispose();
		// 合成最终图像
		BufferedImage combined = new BufferedImage(
				image.getWidth(),
				image.getHeight(),
				BufferedImage.TYPE_INT_ARGB);

		Graphics2D g = combined.createGraphics();
		g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
		g.drawImage(image, 0, 0, null);

		// 设置公章位置（左上角）
		int x = 50;
		int y = 50;

		g.drawImage(resizedSeal, x, y, null);
		g.dispose();

		return combined;
	}

	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));*/
	}

}
