package com.scpyun.platform.jilinsscgsdp.service.impl;

import cn.hutool.core.util.IdUtil;
import com.scpyun.base.bean.Page;
import com.scpyun.base.core.annotation.Api;
import com.scpyun.base.core.annotation.ApiOperation;
import com.scpyun.base.db.service.CommonService;
import com.scpyun.platform.jilinsscgsdp.bean.entity.KeyPersonRatingHistory;
import groovy.util.logging.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * @Author liu
 * @Date 2025/9/26 15:38
 * @PackageName:com.scpyun.platform.jilinsscgsdp.service.impl
 * @ClassName: KeyPersonVisitServiceImpl
 * @Description: TODO
 * @Version 1.0
 */
@Component
@Slf4j
//@Api("人员评分定时任务")
//@Service("keyPersonRatingScheduledTask")
public class KeyPersonRatingScheduledTaskServiceImpl {
    @Autowired
    CommonService commonService;

    private final String SUCCESS = "success";

    private String namespace = "com.scpyun.platform.standard.jilinsscgsdp.keyPersonRatingScheduledTaskDao.";
	private String ratingDictDayNameSpace = "com.scpyun.platform.standard.jilinsscgsdp.keyPersonRatingDictDay.";

	// 记录本次任务的批次号（避免新增数据被本次循环处理）
	private String currentBatchId;
	private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

	/**
	 * 00:30 跑定时任务生成新的评分数据
	 */
//	@Scheduled(cron = "0 30 0 * * ?")
	@Scheduled(cron = "*/20 * * * * ?")
//	@ApiOperation(value = "生成评分数据",desc = "生成评分数据")
	public void ratingScheduledTask() {
		currentBatchId = UUID.randomUUID().toString();

		KeyPersonRatingHistory history = new KeyPersonRatingHistory();
		history.setBatchId(currentBatchId);
		history.setIsHistory("1");
		List<KeyPersonRatingHistory> ratingHistoryList = commonService.findList(namespace + "selectRatingHistoryList", history);

		if (ratingHistoryList == null || ratingHistoryList.isEmpty()) {
			return;
		}

		//处理数据
		for (KeyPersonRatingHistory ratingHistory : ratingHistoryList) {
			handleStatusUpdate(ratingHistory); // 处理状态修改
			handleTaskInsert(ratingHistory);   // 处理数据新增
		}
	}

	/**
	 * 处理状态修改（核心：字符串日期转LocalDate后比较）
	 */
	private void handleStatusUpdate(KeyPersonRatingHistory task) {
		HashMap<String, Object> params = new HashMap<>();
		params.put("id", task.getId());

		int rows = commonService.update(namespace + "updateToOverdue", params);
		if (rows > 0) {
//				System.out.println("任务[" + task.getId() + "]：待办→超期未办");
		}
		int rows1 = commonService.update(namespace + "updateToDue", params);
		if (rows1 > 0) {
//				System.out.println("任务[" + task.getId() + "]：标记为临期");
		}
	}

	/**
	 * 处理数据新增（同样需要转换字符串日期）
	 */
	private void handleTaskInsert(KeyPersonRatingHistory task) {
		LocalDate currentDate = LocalDate.now();

		Map<String, Object> ratingDictDayMap = new HashMap<>();
		ratingDictDayMap.put("rating_dict_type",task.getRatingDictType());
		List<Map<String, Object>> dayResultMapList = commonService.findList(ratingDictDayNameSpace + "selectRatingDictDayList", ratingDictDayMap);

		Map<String, Object> dayResultMap = new HashMap<>();
		if (dayResultMapList != null && dayResultMapList.size() > 0) {
			dayResultMap = dayResultMapList.get(0);
			Integer startDay = Integer.valueOf(dayResultMap.get("rating_start_day").toString());
			Integer overDay = Integer.valueOf(dayResultMap.get("rating_over_day").toString());
			Integer endDay = Integer.valueOf(dayResultMap.get("rating_end_day").toString());

			LocalDate baseDate = LocalDate.parse(task.getPlanEndData());
			long daysSinceBase = ChronoUnit.DAYS.between(baseDate, currentDate);
			//当前日期-截止日期>=设置的开始5
			if (daysSinceBase >= startDay) {
				Map<String, Object> insert = new HashMap<>();
				String id = IdUtil.simpleUUID();
				insert.put("id",id);
				insert.put("rating_dict_type",task.getRatingDictType());
				insert.put("key_person_id",task.getKeyPersonId());

				LocalDate startLocalDate = LocalDate.now();
				Date utilStartDate = Date.from(startLocalDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

				LocalDate overLocalDate = LocalDate.now().plusDays(endDay - overDay);
				Date utilOverDate = Date.from(overLocalDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

				LocalDate endLocalDate = LocalDate.now().plusDays(endDay);
				Date utilEndDate = Date.from(endLocalDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
				insert.put("plan_start_data",utilStartDate);
				insert.put("plan_end_data",utilEndDate);
				insert.put("overdue_date",utilOverDate);
				insert.put("is_history","1");
				insert.put("do_status","0");
				insert.put("is_overdue","0");
				insert.put("batch_id",currentBatchId);

				commonService.insert(namespace + "insert", insert);

				commonService.update(namespace + "updateDoneToHistory", task);
			}
		}
	}


	/**
	 * 字符串日期转LocalDate
	 * @param dateStr 日期字符串（yyyy-MM-dd）
	 * @return LocalDate或null（转换失败时）
	 */
	public static LocalDate parse(String dateStr) {
		if (dateStr == null || dateStr.trim().isEmpty()) {
			return null;
		}
		try {
			return LocalDate.parse(dateStr, FORMATTER);
		} catch (DateTimeParseException e) {
			System.err.println("日期格式错误：" + dateStr + "，应为yyyy-MM-dd");
			return null;
		}
	}

	/**
	 * LocalDate转字符串日期
	 */
	public static String format(LocalDate date) {
		return date == null ? null : date.format(FORMATTER);
	}

}
