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

import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author fxj
 * @Date 2024/12/9
 * @Description
 * @Version 1.0
 */
@Log4j2
@Component
public class ExcelMergeImage {

	/**
	 * @Author fxj
	 * @Description 03格式excel添加电子印章或图片
	 * @Date 15:32 2024/12/9
	 * @Param
	 * @return
	**/
	public  void addPictureToExcel(FileInputStream fis,
													  InputStream imageIs,
													  FileOutputStream fileOut,
													  int SheetNum,String type){
		Workbook workbook = null;
		try {
			workbook = new HSSFWorkbook(fis);
			Sheet sheet = workbook.getSheetAt(SheetNum);
			// 在合适的位置添加印章
			Drawing<?> drawing = sheet.createDrawingPatriarch();
			CreationHelper helper = workbook.getCreationHelper();
			ClientAnchor anchor  = helper.createClientAnchor();
				anchor.setCol1(2);
				anchor.setRow1(0);
				// 按花名册类型特殊处理对应印章的效果
				if (CommonConstants.TWO_STRING.equals(type)){
					anchor.setCol2(5);
					anchor.setRow2(6);
				}else if (CommonConstants.FOUR_STRING.equals(type) || CommonConstants.THREE_STRING.equals(type)){
					anchor.setCol2(5);
					anchor.setRow2(8);
				}else {
					anchor.setCol2(4);
					anchor.setRow2(7);
				}

			// 添加印章图片
			int pictureIdx = workbook.addPicture(IOUtils.toByteArray(imageIs), Workbook.PICTURE_TYPE_PNG);
			drawing.createPicture(anchor, pictureIdx);
			workbook.write(fileOut);
		}catch (Exception e){
			log.error("excel插入电子印章异常：{}",e.getMessage());
		}finally {
			try {
				if (null != fis){
					fis.close();
				}
				if (null != workbook){
					workbook.close();
				}
				if (null != imageIs){
					imageIs.close();
				}
				if (null != fileOut){
					fileOut.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
