package cn.service.impl;

import java.io.File;
import java.io.IOException;
import javax.servlet.ServletOutputStream;
import org.springframework.web.multipart.MultipartFile;
import cn.report.excel.easyexcel.api.EasyExcel;
import cn.report.excel.easyexcel.api.ExcelWriter;
import cn.report.excel.easyexcel.api.support.ExcelTypeEnum;
import cn.report.excel.easyexcel.api.write.builder.ExcelWriterBuilder;
import cn.report.excel.easyexcel.api.write.builder.ExcelWriterSheetBuilder;
import cn.report.excel.easyexcel.api.write.metadata.WriteSheet;
import cn.report.excel.easyexcel.api.write.style.column.LongestMatchColumnWidthStyleStrategy;
import cn.report.excel.easyexcel.custom.base.EasyExcelParam;
import cn.report.excel.util.EasyExcelUtil;
import cn.util.core.IsKit;
import cn.util.http.FileKit;


public class EasyExcelService
{
	private EasyExcelService() {}
	/**
	 * 导出2007版Excel
	 */
	public static void exportExcel2007Format(EasyExcelParam params) throws IOException {
		exportExcel(params);
	}
	
	private static void exportExcel(EasyExcelParam params) throws IOException
	{
		 //添加自己的验证条件
		 //Validate.isTrue(params.isValid(), "参数错误!");

		ServletOutputStream outputStream = null;
		ExcelWriterSheetBuilder sheetBuilder = EasyExcel.writerSheet(params.getSheetNo());
		sheetBuilder.sheetName(params.getSheetName());
		//表头、内容样式设置
		if(IsKit.isNotNullOrEmpty(params.getCellStyle())) {
			sheetBuilder.registerWriteHandler(params.getCellStyle());
		}
	
		if(IsKit.isNotNullOrEmpty(params.getHeaderLine())) {
			sheetBuilder.registerWriteHandler(params.getHeaderLine());
		}
		
		//如需要表头，表头类别
		if(params.getNeedHead()) {
			if(IsKit.isNotNullOrEmpty(params.getHeader())) {
				sheetBuilder.head(EasyExcelUtil.head(params.getHeader()));
			}
			//目前只支持两级标题
			if(params.getHeaderNum() == 2) {
				// 第一行大标题样式设置
				if(IsKit.isNotNullOrEmpty(params.getHeaderStyle())) {
					sheetBuilder.registerWriteHandler(params.getHeaderStyle());
				}				
				sheetBuilder.relativeHeadRowIndex(1);//设置默认样式及写入头信息开始的行数
			}
		}
		if(IsKit.isNotNullOrEmpty(params.getWaterMark())) {
			sheetBuilder.registerWriteHandler(params.getWaterMark());
		}
		if(IsKit.isNotNullOrEmpty(params.getCellMerge())) {
			sheetBuilder.registerWriteHandler(params.getCellMerge());
		}
		
		//自动列宽
		sheetBuilder.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy());
		WriteSheet sheet = sheetBuilder.build();

		ExcelWriterBuilder builder = new ExcelWriterBuilder();
		builder.excelType(ExcelTypeEnum.XLSX);
		builder.inMemory(true);
		//builder.sheet(params.getSheetName()); 系统报错
		
		if(IsKit.isNotNullOrEmpty(params.getPassword())) {
			builder.password(params.getPassword());
		}
		
		
		//是否需要表头  
		builder.needHead(params.getNeedHead());
		//builder.head(params.getDataModelClazz());

		if("File".equalsIgnoreCase(params.getStreamType())) {
			builder.file(new File(params.getFileName()));	
		}
		else {
			FileKit.prepareRespond_xlsx(params.getFileName(), params.getResponse());
			outputStream = params.getResponse().getOutputStream();
			builder.file(outputStream);
		}

		//保护文档
		builder.registerWriteHandler(params.getStyleConfig());

		ExcelWriter writer = builder.build();
		writer.write(params.getData(), sheet);

		if (IsKit.isNotNullOrEmpty(writer)) {
			writer.finish();
		}
		if (IsKit.isNotNullOrEmpty(outputStream)) {
			outputStream.close();
		}
	}


	private static final String EXCEL_SECRET_CODE = "intelligence-password";
	private static final String EXCEL_VERSION = "1.0";
	/**
	 * 校验导入文件是否是Excel格式
	 */
	public static boolean checkExcelStyle(MultipartFile file) {
		String filename = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
		return filename.equals(ExcelTypeEnum.XLSX.getValue());
	}
	/**
	 * 检查Excel的密码
	 */
	public static boolean checkExcelPassword(String secretCode) {
		return EXCEL_SECRET_CODE.equals(secretCode);
	}
	/**
	 * 检查Excel的密码
	 */
	public static boolean checkExcelVersion(String version) {
		return EXCEL_VERSION.equals(version);
	}


}
/*
调用示例
String fileName ="D:\\data\\EasyTest6.xlsx";
// 内容样式
WriteCellStyle contentWriteCellStyle = EasyExcelUtil.getContentStyle();
HorizontalCellStyleStrategy horizontalCellStyleStrategy =
		new HorizontalCellStyleStrategy(EasyExcelUtil.getHeadStyle(), contentWriteCellStyle);
List<DemoData> data = data();
String text = "       工资\n年龄";
String slashType = "LEFT_BOTTOM";
String[] header = {"宿6舍","姓名","学号","状态","归寝时间"};
String bigtitle= "实时离寝情5况报表";
//获取要导出的数据
//获取导出数据总条数 传入做校验格式使用
List<Integer> collect = new ArrayList<Integer>();//deviceData.stream().map(TestVo::getId).collect(Collectors.toList());
collect.add(7);
//设置excel名称以及sheet名称，是否需要表头
EasyExcelParam params = new EasyExcelParam(
		"File",fileName,"成绩",
		true,header, 
		new SamTitleWriteHandler(bigtitle,header),2, 
		//null,2,
		new SamCellDrawSlashHandler(1,0,2,1,text,slashType),
		horizontalCellStyleStrategy,        		
		data, 
		DemoData.class,	null);
//设置样式 校验格式
params.setStyleConfig(new ExcelStyleConfig(
		Lists.newArrayList(4),//columnList 锁定列？？？true
		Lists.newArrayList(0), //columnNumLis
		null,//Lists.newArrayList(3,4), //OKhiddenIndices
		collect //rowNumList
		));
//导出数据
cn.service.report.impl.EasyExcelService.exportExcel2007Format(params);
*/
//https://blog.csdn.net/weixin_44990626/article/details/107389814?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~aggregatepage~first_rank_ecpm_v1~rank_v31_ecpm-2-107389814.pc_agg_new_rank&utm_term=EasyExcel+%E8%AE%BE%E7%BD%AE%E5%88%97%E5%8F%AA%E8%AF%BB&spm=1000.2123.3001.4430