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

import com.scpyun.base.core.annotation.Api;
import com.scpyun.base.core.annotation.ApiOperation;
import com.scpyun.base.db.service.CommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author liu
 * @Date 2025/9/26 15:38
 * @PackageName:com.scpyun.platform.jilinsscgsdp.service.impl
 * @ClassName: KeyPersonVisitServiceImpl
 * @Description: TODO
 * @Version 1.0
 */
//@Api("重度人员回访计划定时任务")
//@Service("keyPersonVisitRecordScheduledTask")
@Component
@Slf4j
public class KeyPersonVisitRecordScheduledTaskServiceImpl {
    @Autowired
    CommonService commonService;

    private final String SUCCESS = "success";

    private String namespace = "com.scpyun.platform.standard.jilinsscgsdp.keyPersonVisitRecordScheduledTaskDao.";

	/**
	 * 每天00:10生成回访“待办”记录
	 */
//	@Scheduled(cron = "0 30 0 * * ?")
	@Scheduled(cron = "0/20 * * * * ?")
//	@ApiOperation(value = "生成",desc = "生成")
	public void generateDailyVisitTodos() {
		log.info("定时任务 - 开始生成回访计划");
		List<Map<String, Object>> activePlans = commonService.findList(namespace + "selectActiveVisitPlans", new HashMap<>());
		if (activePlans == null || activePlans.isEmpty()) {
			return;
		}
		LocalDate today = LocalDate.now();

		for (Map<String, Object> plan : activePlans) {
			String planId = String.valueOf(plan.get("id"));
			String planName = String.valueOf(plan.get("plan_name"));
			String planType = String.valueOf(plan.get("plan_type"));
			String ratingDictType = String.valueOf(plan.get("rating_dict_type"));
			String ratingType = String.valueOf(plan.get("rating_type"));
			int startDay = Integer.parseInt(String.valueOf(plan.get("visit_start_day")));
			int endDay = Integer.parseInt(String.valueOf(plan.get("visit_end_day")));
			int overdueDays = 0;
			Object overdueObj = plan.get("overdue_warning_day");
			if (overdueObj != null) {
				try { overdueDays = Integer.parseInt(String.valueOf(overdueObj)); } catch (Exception ignored) {}
				if (overdueDays < 0) { overdueDays = 0; }
			}

			Map<String, Object> personQuery = new HashMap<>();
			personQuery.put("rating_dict_type", ratingDictType);
			personQuery.put("rating_type", ratingType);

			List<Map<String, Object>> persons;
			if ("6".equals(ratingDictType)) {
				persons = commonService.findList(namespace + "selectPersonsForMinorByPlan", personQuery);
			} else {
				persons = commonService.findList(namespace + "selectPersonsForKeyPersonByPlan", personQuery);
			}
			if (persons == null || persons.isEmpty()) {
				continue;
			}

			for (Map<String, Object> person : persons) {
				String personId = String.valueOf(person.get("person_id"));

				Map<String, Object> param = new HashMap<>();
				param.put("person_id", personId);

				// 标记可能已过期的“待办”记录
				Map<String, Object> latestBefore = commonService.getObject(namespace + "selectLatestRecordByPerson", param);
				if (latestBefore != null) {
					commonService.update(namespace + "markOverdueIfExpired", latestBefore);
				}
				// 重新获取最新记录
				Map<String, Object> latest = commonService.getObject(namespace + "selectLatestRecordByPerson", param);

				// 4.3 无任何回访记录：直接新增
				if (latest == null) {
					LocalDate planStart = today;
					LocalDate planEnd = today.plusDays(Math.max(0, endDay - startDay));
					Map<String, Object> insert = new HashMap<>();
					insert.put("person_id", personId);
					insert.put("key_person_visit_id", planId);
					insert.put("plan_name", planName);
					insert.put("plan_type", planType);
					insert.put("rating_dict_type", ratingDictType);
					insert.put("rating_type", ratingType);
					insert.put("plan_start_data", planStart.toString());
					insert.put("plan_end_data", planEnd.toString());
					if (overdueDays > 0) {
						LocalDate overdueDate = planEnd.minusDays(overdueDays);
						insert.put("overdue_date", overdueDate.toString());
					}
					commonService.insert(namespace + "insertVisitRecord", insert);
					continue;
				}

				String statusStr = String.valueOf(latest.get("do_status"));
				int status = -1;
				try { status = Integer.parseInt(statusStr); } catch (Exception ignored) {}

				// 4.2 一个“待办”限制：如仍为“待办”，则不生成；
				if (status == 0) {
					continue;
				}

				// 4.4 最新为“已办(1)”或“超期未办(2)”：达到起始天数生成新“待办”
				Object planEndObj = latest.get("plan_end_date");
				LocalDate baseDate = planEndObj != null ? LocalDate.parse(String.valueOf(planEndObj)) : today;
				long daysSinceBase = ChronoUnit.DAYS.between(baseDate, today);
				if (daysSinceBase >= startDay) {
					LocalDate planStart = baseDate.plusDays(startDay);
					LocalDate planEnd = baseDate.plusDays(endDay);
					Map<String, Object> insert = new HashMap<>();
					insert.put("person_id", personId);
					insert.put("key_person_visit_id", planId);
					insert.put("plan_name", planName);
					insert.put("plan_type", planType);
					insert.put("rating_dict_type", ratingDictType);
					insert.put("rating_type", ratingType);
					insert.put("plan_start_data", planStart.toString());
					insert.put("plan_end_data", planEnd.toString());
					if (overdueDays > 0) {
						LocalDate overdueDate = planEnd.minusDays(overdueDays);
						insert.put("overdue_date", overdueDate.toString());
					}
					commonService.insert(namespace + "insertVisitRecord", insert);
				}
			}
		}
		log.info("定时任务 - 回访计划生成结束");
	}

	/**
	 * 每天00:10：将所有“待办”中超过临期日期(overdue_date)的记录标记为已临期(is_overdue=1)
	 * 示例：overdue_date=2025-05-05，则在2025-05-06触发任务后置为1
	 */
//	@Scheduled(cron = "0 10 0 * * ?")
	@Scheduled(cron = "0/20 * * * * ?")
//	@ApiOperation(value = "标记临期", desc = "超过 overdue_date 将 is_overdue 置为 1")
	public void markOverdueByOverdueDate() {
		log.info("定时任务 - 更新回访计划临期状态");
		commonService.update(namespace + "markOverdueByOverdueDate", new HashMap<>());
		log.info("定时任务 - 回访计划临期状态结束");
	}
}
