package com.yifu.cloud.plus.v1.yifu.archives.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yifu.cloud.plus.v1.yifu.archives.entity.EmployeeRegistrationPre;
import com.yifu.cloud.plus.v1.yifu.archives.service.EmployeeRegistrationPreService;
import com.yifu.cloud.plus.v1.yifu.archives.service.ScheduleService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.SendMessageUpdateVo;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.PostConstruct;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

@Service
public class ScheduleServiceImpl implements ScheduleService {

	@Autowired
	private EmployeeRegistrationPreService registrationPreService;
	@Autowired
	private TaskScheduler taskScheduler;
	@Autowired
	private TransactionTemplate transactionTemplate;

	// 用于存储任务 ID 和 ScheduledFuture 的映射关系
	private final Map<String, ScheduledFuture<?>> scheduledTasks = new ConcurrentHashMap<>();

	// 应用启动时初始化未处理的任务
	@PostConstruct
	public void initSchedule() {
		List<EmployeeRegistrationPre> records = registrationPreService.list(Wrappers.<EmployeeRegistrationPre>query()
				.lambda().ge(EmployeeRegistrationPre::getExpectedCollectionTime,LocalDateTime.now())
				.eq(EmployeeRegistrationPre::getProcessStatus,CommonConstants.ZERO_STRING));
		records.forEach(this::scheduleTask);
	}

	// 调度单个任务
	@Override
	public void scheduleTask(EmployeeRegistrationPre record) {
		Instant triggerTime = record.getExpectedCollectionTime().atZone(ZoneId.systemDefault()).toInstant();
		String taskId = record.getId();
		
		// 如果任务已存在，先取消旧任务
		removeTask(taskId);
		
		// 创建新任务并保存引用
		ScheduledFuture<?> future = taskScheduler.schedule(() -> executeTask(taskId), triggerTime);
		scheduledTasks.put(taskId, future);
	}

	// 执行发送短信操作（事务内处理）
	@Override
	public void executeTask(String aId) {
		transactionTemplate.execute(status -> {
			List<SendMessageUpdateVo> voList = new ArrayList<>();
			SendMessageUpdateVo updateVo = new SendMessageUpdateVo();
			updateVo.setId(aId);
			voList.add(updateVo);
			registrationPreService.batchSendMessage(voList, CommonConstants.ONE_STRING);
			return null;
		});
	}

	/**
	 * @Author fxj
	 * @Description 删除已经存在的任务
	 * @Date 14:17 2026/4/3
	 * @Param 
	 * @return 
	**/
	@Override
	public void removeTask(String aId) {
		// 从调度器中取消任务
		ScheduledFuture<?> future = scheduledTasks.remove(aId);
		if (future != null) {
			future.cancel(false); // false 表示不中断正在执行的任务
		}
	}

}
