package org.sky.scientific.excel.converter;


import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.sky.core.tool.utils.StringUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DefaultDateConverter implements Converter<Date> {

	private final String[] patterns = {"yyyy-MM-dd", "yyyy/MM/dd", "yyyy年MM月dd日", "yyyy-MM-dd HH:mm:ss"};

	@Override
	public Date convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
		if (cellData == null || cellData.getType() == CellDataTypeEnum.EMPTY) {
			return null; // 日期为空时返回null
		}

		try {
			switch (cellData.getType()) {
				case NUMBER:
					// 处理Excel数字格式的日期
					return org.apache.poi.ss.usermodel.DateUtil.getJavaDate(cellData.getNumberValue().doubleValue());
				case STRING:
					String dateString = cellData.getStringValue();
					if (StringUtil.isBlank(dateString)) {
						return null;
					}
					return parseDate(dateString.trim());
				default:
					return null;
			}
		} catch (Exception e) {
			return null;
		}
	}

	private Date parseDate(String dateString) {
		for (String pattern : patterns) {
			try {
				SimpleDateFormat sdf = new SimpleDateFormat(pattern);
				sdf.setLenient(false);
				return sdf.parse(dateString);
			} catch (ParseException e) {
				// 尝试下一种格式
			}
		}
		return null; // 所有格式都不匹配时返回null
	}

	@Override
	public CellDataTypeEnum supportExcelTypeKey() {
		return CellDataTypeEnum.STRING;
	}

	@Override
	public Class<?> supportJavaTypeKey() {
		return Date.class;
	}
}
