package org.sky.scientific.excel.handle;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.sky.scientific.pojo.vo.DailyHours;
import org.sky.scientific.pojo.vo.TechnicianHoursMonthlyVO;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class TechnicianWorkStatisticsMergeStrategy implements SheetWriteHandler {

	private final Integer year;
	private final Integer month;
	private final List<TechnicianHoursMonthlyVO> list;

	public TechnicianWorkStatisticsMergeStrategy(List<TechnicianHoursMonthlyVO> list, Integer year, Integer month) {
		this.list = list;
		this.year = year;
		this.month = month;
	}

	@Override
	public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
		// 不需要实现
	}

	@Override
	public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {

		Workbook workbook = writeWorkbookHolder.getWorkbook();
		Sheet sheet = workbook.getSheetAt(0);

		LocalDate startDate = LocalDate.of(year, month, 1);
		int daysInMonth = startDate.lengthOfMonth();
		int totalColumns = daysInMonth + 8; // 天数 + 8个固定列

		// 1. 合并标题行（第一行合并所有列）
		CellRangeAddress titleMerge = new CellRangeAddress(0, 0, 0, totalColumns - 1);
		sheet.addMergedRegion(titleMerge);

		// 2. 合并纵向表头行（第2行）
		//序号合并
		CellRangeAddress xhMerge = new CellRangeAddress(1, 2, 0, 0);
		sheet.addMergedRegion(xhMerge);

		// 工号合并
		CellRangeAddress numberMerge = new CellRangeAddress(1, 2, 1, 1);
		sheet.addMergedRegion(numberMerge);

		// 姓名合并
		CellRangeAddress nameMerge = new CellRangeAddress(1, 2, 2, 2);
		sheet.addMergedRegion(nameMerge);

		// 身份证号码合并
		CellRangeAddress idCardMerge = new CellRangeAddress(1, 2, 3, 3);
		sheet.addMergedRegion(idCardMerge);

		// 科研人员类别合并
		CellRangeAddress personTypeMerge = new CellRangeAddress(1, 2, 4, 4);
		sheet.addMergedRegion(personTypeMerge);

		// 类别合并
		CellRangeAddress typeMerge = new CellRangeAddress(1, 2, 5, 5);
		sheet.addMergedRegion(typeMerge);

		// 合计合并
		CellRangeAddress totalMerge = new CellRangeAddress(1, 2, totalColumns-2, totalColumns-2);
		sheet.addMergedRegion(totalMerge);

		// 工时分配率合并
		CellRangeAddress rateMerge = new CellRangeAddress(1, 2, totalColumns-1, totalColumns-1);
		sheet.addMergedRegion(rateMerge);

		for (int i = 0; i < list.size(); i++) {

			// 序号合并
			CellRangeAddress merge0 = new CellRangeAddress(3+i*2, 4+i*2, 0, 0);
			sheet.addMergedRegion(merge0);

			// 工号合并
			CellRangeAddress merge1 = new CellRangeAddress(3+i*2, 4+i*2, 1, 1);
			sheet.addMergedRegion(merge1);

			// 姓名合并
			CellRangeAddress merge2 = new CellRangeAddress(3+i*2, 4+i*2, 2, 2);
			sheet.addMergedRegion(merge2);

			// 身份证号码合并
			CellRangeAddress merge3 = new CellRangeAddress(3+i*2, 4+i*2, 3, 3);
			sheet.addMergedRegion(merge3);

			// 科研人员类别合并
			CellRangeAddress merge4 = new CellRangeAddress(3+i*2, 4+i*2, 4, 4);
			sheet.addMergedRegion(merge4);
		}

	}


	/**
	 * 构建数据行
	 */
	public static List<List<Object>> buildData(List<TechnicianHoursMonthlyVO> list, Integer year, Integer month) {
		List<List<Object>> data = new ArrayList<>();

		LocalDate startDate = LocalDate.of(year, month, 1);
		int daysInMonth = startDate.lengthOfMonth();
		DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
		DateTimeFormatter weekFormatter = DateTimeFormatter.ofPattern("E", Locale.CHINA);
		DateTimeFormatter dayFormatter = DateTimeFormatter.ofPattern("d");

		// 第一行：标题行
		List<Object> titleRow = new ArrayList<>();
		titleRow.add( year + "年" + month + "月研发工时汇总表");
		for (int i = 1; i < daysInMonth + 8; i++) { // 8个固定列
			titleRow.add("");
		}
		data.add(titleRow);

		// 第二行：纵向表头标题
		List<Object> verticalHeaderRow = new ArrayList<>();
		verticalHeaderRow.add("序号");
		verticalHeaderRow.add("工号");
		verticalHeaderRow.add("姓名");
		verticalHeaderRow.add("身份证号码");
		verticalHeaderRow.add("科研人员类别");
		verticalHeaderRow.add("类别");
		//第二行：周几行
		for (int i = 1; i <= daysInMonth; i++) {
			LocalDate date = LocalDate.of(year, month, i);
			verticalHeaderRow.add(date.format(weekFormatter).substring(1));
		}

		verticalHeaderRow.add("合计");
		verticalHeaderRow.add("工时分配率%");
		data.add(verticalHeaderRow);

		// 第三行：日期数字行
		List<Object> dayRow = new ArrayList<>();
		dayRow.add("");
		dayRow.add("");
		dayRow.add("");
 		dayRow.add("");
		dayRow.add("");
		dayRow.add("");
		for (int day = 1; day <= daysInMonth; day++) {
			LocalDate date = LocalDate.of(year, month, day);
			dayRow.add(date.format(dayFormatter));
		}
		dayRow.add("");
		dayRow.add("");
		data.add(dayRow);

		// 第4行开始：数据行
		int index = 0;
		for (TechnicianHoursMonthlyVO vo : list) {

			for(int i = 0; i < 2; i++){
				List<Object> dataRow = new ArrayList<>();
				// 序号
				dataRow.add(vo.getXh());
				// 工号
				dataRow.add(vo.getNumber());
				//姓名
				dataRow.add(vo.getName());
				// 身份证号码
				dataRow.add(vo.getIdCard());
				// 科研人员类别
				dataRow.add(vo.getPersonnelType());

				dataRow.add((index%2==0)?"研发工时":"非研发工时");

				// 每日考勤数据
				Map<String, Double> dailyMap = new HashMap<>();

				for (DailyHours daily : vo.getDailyHoursList()) {
					dailyMap.put(daily.getWorkDate(), (index%2==0)?daily.getWorkHours():daily.getUnworkHours());
				}

				for (int day = 1; day <= daysInMonth; day++) {
					LocalDate currentDate = LocalDate.of(year, month, day);
					String dateKey = currentDate.format(dateFormatter);
					dataRow.add(dailyMap.getOrDefault(dateKey, 0.0));
				}
				//合计
				dataRow.add((index%2==0)?vo.getWorkHoursTotal():vo.getUnworkHoursTotal());
				//工时分配率
				dataRow.add(BigDecimal.valueOf(index%2==0?vo.getWorkHoursRate()*100.00:vo.getUnworkHoursRate()*100.00).setScale(2, RoundingMode.HALF_UP));
				data.add(dataRow);
				index ++;
			}
		}
		return data;
	}

}
