package org.security.common.handler;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.ss.usermodel.*;


/**
 * @author Create by wzf
 * @date 2022/5/30 14:46
 * 实现CellWriteHandler接口, 实现对单元格样式的精确控制
 */
public class CustomCellWriteHandler implements CellWriteHandler {
	@Override
	public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
								 Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {

	}

	/**
	 * 单元格创建之后(没有写入值)
	 *
	 * @param writeSheetHolder
	 * @param writeTableHolder
	 * @param cell
	 * @param head
	 * @param relativeRowIndex
	 * @param isHead
	 */
	@Override
	public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell,
								Head head, Integer relativeRowIndex, Boolean isHead) {

	}

	@Override
	public void afterCellDataConverted(CellWriteHandlerContext context) {

	}

	/**
	 * 单元格处理后(已写入值): 设置第一行第一列的头超链接到EasyExcel的官网(本系统的导出的excel 0,1两行都是头,所以只设置第一行的超链接)
	 * 这里再进行拦截的单元格样式设置的话,前面该样式将全部失效
	 *
	 * @param context
	 */
	@Override
	public void afterCellDispose(CellWriteHandlerContext context) {
		// 设置超链接
		if (Boolean.TRUE.equals(context.getHead() && context.getCell().getRowIndex() == 0) && context.getCell().getColumnIndex() == 0) {
			CreationHelper helper = context.getWriteSheetHolder().getSheet().getWorkbook().getCreationHelper();
			Hyperlink hyperlink = helper.createHyperlink(HyperlinkType.URL);
			hyperlink.setAddress("https://github.com/alibaba/easyexcel");
			context.getCell().setHyperlink(hyperlink);
		}
		// 精确设置单元格格式
		boolean bool = context.getHead() && context.getCell().getRowIndex() == 1 &&
			("请求参数".equals(context.getCell().getStringCellValue()) || "请求Body".equals(context.getCell().getStringCellValue()));
		if (bool) {
			// 获取工作簿
			Workbook workbook = context.getWriteSheetHolder().getSheet().getWorkbook();
			CellStyle cellStyle = workbook.createCellStyle();

			Font cellFont = workbook.createFont();
			cellFont.setBold(Boolean.TRUE);
			cellFont.setFontHeightInPoints((short) 14);
			cellFont.setColor(IndexedColors.SEA_GREEN.getIndex());
			cellStyle.setFont(cellFont);
			context.getCell().setCellStyle(cellStyle);
		}
	}

}
