package org.springblade.modules.order.utils;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.excel.listener.DataListener;
import org.springblade.core.excel.util.ExcelUtil;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * @author hongzq
 */
public class ExcelReader {

	private static Logger logger = LoggerFactory.getLogger(ExcelReader.class);

	public static <T> List<T> readExcel(MultipartFile excel, Class<T> clazz) {
		DataListener<T> dataListener = new DataListener<T>() {
			@Override
			public void invokeHeadMap(Map headMap, AnalysisContext context) {
				logger.info("读取到的表头: {}", headMap);
				checkExcelHeader(headMap, clazz);
			}
		};
		ExcelReaderBuilder builder = ExcelUtil.getReaderBuilder(excel, dataListener, clazz);
		if (builder == null) {
			return null;
		} else {
			builder.doReadAll();
			return dataListener.getDataList();
		}
	}

	private static void checkExcelHeader(Map headMap, Class clazz) {
		Field[] fields = clazz.getDeclaredFields();
		List<ExcelProperty> list = new ArrayList<>();
		for (Field field : fields) {
			ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
			if (excelProperty != null) {
				list.add(excelProperty);
			}
		}
		list.sort(Comparator.comparingInt(ExcelProperty::order));
		for (int i = 0; i < list.size(); i++) {
			ExcelProperty excelProperty = list.get(i);
			System.out.println(excelProperty.value());
			System.out.println(excelProperty.value()[0]);
			System.out.println(headMap.get(i));
			if (!excelProperty.value()[0].equals(headMap.get(i))) {
				throw new ExcelAnalysisException("模板不匹配");
			}
		}
	}
}
