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;

@Service
public class ScheduleServiceImpl implements ScheduleService {

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

	// 应用启动时初始化未处理的任务
	@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();
		taskScheduler.schedule(() -> executeTask(record.getId()), triggerTime);
	}

	// 执行发送短信操作（事务内处理）
	@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;
		});
	}

}
