package org.sky.scientific.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;
import lombok.Data;
import org.sky.core.tool.utils.StringUtil;
import org.sky.scientific.pojo.vo.DailyAttendance;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Data
public class XmAssetHoursListener implements ReadListener<Map<Integer, String>> {

	private static final int HEADER_ROW_1 = 1; // 星期行(0-based)
	private static final int HEADER_ROW_2 = 2; // 日期行
	private static final int DATA_START_ROW = 3; // 数据开始行

 	private List<String> dateHeaders = new ArrayList<>();
	private List<XmAssetHoursExcel> records = new ArrayList<>();
	private boolean headersProcessed = false;
	private String yearAndMonth;

	@Override
	public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
		int rowIndex = context.readRowHolder().getRowIndex();

		 if (rowIndex == HEADER_ROW_2) {
			// 处理日期行
			dateHeaders = extractHeaders(headMap, 8);
			headersProcessed = true;
		}
	}

	private List<String> extractHeaders(Map<Integer, ReadCellData<?>> headMap, int startCol) {
		List<String> headers = new ArrayList<>();
		headMap.entrySet().stream()
			.filter(entry -> entry.getKey() >= startCol)
			.sorted(Map.Entry.comparingByKey())
			.forEach(entry -> {
				String stringValue = entry.getValue().getStringValue();
				if(StringUtil.isBlank(stringValue)){
					BigDecimal numberValue = entry.getValue().getNumberValue();
					if(numberValue != null){
						headers.add(numberValue.intValue()<=9?"0"+numberValue.intValue() : numberValue.intValue()+"");
					}
				}else {
					headers.add(stringValue);
				}


			});
		return headers;
	}

	@Override
	public void invoke(Map<Integer, String> data, AnalysisContext context) {
		if (!headersProcessed || context.readRowHolder().getRowIndex() < DATA_START_ROW) {
			return;
		}

		// 跳过空行
		if (data == null || data.isEmpty() || data.values().stream().allMatch(v -> v == null || v.trim().isEmpty())) {
			return;
		}

		XmAssetHoursExcel record = new XmAssetHoursExcel();

		// 解析固定列
		record.setSerialNumber(safeParseInt(data.get(0)));
		record.setXmbh(data.get(1));
		record.setXmmc(data.get(2));
		record.setZcbm(data.get(3));
		record.setZcmc(data.get(4));
		record.setZclb(data.get(5));
		record.setYt(data.get(6));

		// 解析每日工时数据
 		for (int i = 0; i < dateHeaders.size(); i++) {
			String hoursStr = data.get(i + 8); // 工时数据从第5列开始
			//没有填报的日期，跳过
			if (hoursStr != null && !hoursStr.trim().isEmpty()) {
				try {
					DailyAttendance daily = new DailyAttendance();
					daily.setWorkDate(yearAndMonth + dateHeaders.get(i));
					daily.setWorkHours(safeParseDouble(hoursStr));
					record.getDailyAttendances().add(daily);
				} catch (NumberFormatException e) {
					System.err.printf("解析错误: 资产[%s] 日期[%s] 值[%s]%n",
						record.getZcmc(), dateHeaders.get(i), hoursStr);
				}
			}
		}

		records.add(record);
	}

	@Override
	public void doAfterAllAnalysed(AnalysisContext context) {
		System.out.println("科研仪器设备工时数据解析完成，共解析 " + records.size() + " 条记录");
	}


	private Integer safeParseInt(String value) {
		try {
			return value == null || value.trim().isEmpty() ? null : Integer.parseInt(value.trim());
		} catch (NumberFormatException e) {
			return null;
		}
	}

	private Double safeParseDouble(String value) {
		try {
			return value == null || value.trim().isEmpty() ? null : Double.parseDouble(value.trim());
		} catch (NumberFormatException e) {
			return null;
		}
	}
}
