package com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.insurances.entity.TEmployeeInsurancePre;
import com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.ScheduleService;
import com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.TEmployeeInsurancePreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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 TEmployeeInsurancePreService insurancePreService;

	@Autowired
	private TaskScheduler taskScheduler;

	@Autowired
	@Qualifier("insurancesTransactionTemplate")
	private TransactionTemplate transactionTemplate;

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

	// 调度单个任务
	@Override
	public void scheduleTask(TEmployeeInsurancePre 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<String> idList = new ArrayList<>();
			idList.add(aId);
			insurancePreService.batchDispatcherInsurance(idList,CommonConstants.ONE_STRING, false);
			return null;
		});
	}

}
