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.DateUtil;
import org.sky.scientific.pojo.vo.DailyAttendance;

import java.math.BigDecimal;
import java.util.*;

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

	private static final int HEADER_ROW_2 = 3; // 日期行
	private static final int DATA_START_ROW = 4; // 数据开始行

	private static final int DATA_START_COL = 7;

	private List<String> dateHeaders = new ArrayList<>();
	private List<XmTechnicianHoursExcel> 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, DATA_START_COL);
			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 -> {
				BigDecimal numberValue = entry.getValue().getNumberValue();
				if (numberValue != null) {
					String str = formatExcelDate(numberValue.intValue());
					headers.add(str);
				}
			});
		return headers;
	}
	public static String formatExcelDate(int day){
		Calendar calendar = new GregorianCalendar(1900,0,-1);
		Date date = calendar.getTime();
		return DateUtil.format(DateUtil.plusDays(date, day), "yyyyMMdd");
	}

	@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;
		}

		XmTechnicianHoursExcel record = new XmTechnicianHoursExcel();

		// 解析固定列
		record.setSerialNumber(safeParseInt(data.get(0)));
		record.setXmbh(data.get(1));
		record.setXmmc(data.get(2));
		record.setNumber(data.get(3));
		record.setNamme(data.get(4));
		record.setIdCard(data.get(5));
		record.setPersonnelType(data.get(6));

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