package cn.superdesk.uniorder.common.excel.utils;

import cn.superdesk.uniorder.common.excel.ExcelImportBaseEventListener;
import cn.superdesk.uniorder.common.excel.converters.artificial.CustomStringDateConverter;
import cn.superdesk.uniorder.common.excel.model.ExcelRow;
import cn.superdesk.uniorder.common.security.dto.LoginSysUser;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import lombok.Builder;

import java.io.InputStream;
import java.util.List;

/**
 * @Description: Java类作用描述
 * @Author: linjinyu
 * @CreateDate: 2021/8/24 上午11:10
 * @UpdateUser: linjinyu
 * @UpdateDate: 2021/8/24 上午11:10
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Builder
public class ExcelImportReaderUtils {

	private LoginSysUser loginSysUser;

	private InputStream inputStream;

	private String batchId;
	/**
	 * sheet位置 从 1 开始
	 * // 标记 readSheetNumber from 1
	 * // 标记 readSheetNumber from 0
	 */
	private int    readSheetNumber;
	/**
	 * 开始读取行的位置,从0开始
	 */
	private int    headRowNumber;

	/**
	 * 读取excel 这东西还tmd有特殊性哦,还不能这样写哦
	 *
	 * @param headClazz 目标类型
	 * @param <T>
	 * @return
	 */
	public <T extends ExcelRow> List<T> read(Class<T> headClazz) {

		ExcelImportBaseEventListener<T> excelRowDataAnalysisEventListener = new ExcelImportBaseEventListener<>(headClazz);
		excelRowDataAnalysisEventListener
				.setHeadRowNumber(headRowNumber);

		// 标记 readSheetNumber from 1
//		ExcelReader excelReader = new ExcelReader(
//				inputStream,
//				null,
//				excelRowDataAnalysisEventListener,
//				true
//		);
//		excelReader.read(new Sheet(readSheetNumber, headRowNumber, headClazz));

		// 标记 readSheetNumber from 0
		ExcelReader excelReader = null;

		try {
			excelReader = EasyExcel.read(
					inputStream,
					headClazz,
					excelRowDataAnalysisEventListener
			).registerConverter(new CustomStringDateConverter())
					.customObject(headClazz).build();

			ReadSheet readSheet = EasyExcel
					.readSheet(readSheetNumber)
					.headRowNumber(headRowNumber)
					.build();

			excelReader.read(readSheet);

		} finally {

			if (excelReader != null) {
				// 这里千万别忘记关闭,读的时候会创建临时文件,到时磁盘会崩的
				excelReader.finish();
			}
		}

		return excelRowDataAnalysisEventListener.getExcelRows();
	}

}
