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 AttendanceMonthlyDataListener 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> dayOfWeekHeaders = new ArrayList<>();
	private List<String> dateHeaders = new ArrayList<>();
	private List<AttendanceMonthlyExcel> 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_1) {
			// 处理星期行
			dayOfWeekHeaders = extractHeaders(headMap, 5);
		} else if (rowIndex == HEADER_ROW_2) {
			// 处理日期行
			dateHeaders = extractHeaders(headMap, 5);
			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;
		}

		AttendanceMonthlyExcel record = new AttendanceMonthlyExcel();

		// 解析固定列
		record.setSerialNumber(safeParseInt(data.get(0)));
		record.setName(data.get(1));
		record.setNumber(data.get(2));
		record.setIdCard(data.get(3));
		record.setPersonnelType(data.get(4));

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

		// 解析月度汇总数据(最后两列)
		int lastCol = 5 + maxDays;
		if (data.size() > lastCol) {
			record.setMonthlyHours(safeParseDouble(data.get(lastCol)));
			record.setMonthlyDays(safeParseDouble(data.get(lastCol + 1)));
		}
 		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;
		}
	}
}
