package org.security.trans.taskCheck.device;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.security.common.Constant;
import org.security.common.util.DataFormatUtil;
import org.security.ht.entity.basic.Device;
import org.security.trans.basic.service.IDeviceService;
import org.security.trans.dailyDuties.entity.DeviceInspection;
import org.security.trans.dailyDuties.service.IDeviceInspectionService;
import org.springblade.core.tool.utils.Func;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zj 2022/4/27
 */
@Slf4j
@Component
@AllArgsConstructor
public class DeviceDeadlineCheckTask {
	private final IDeviceInspectionService deviceInspectionService;
	private final IDeviceService deviceService;

	/**
	 * 检查设备检查任务是否超时
	 */
	@Async("securityThreadPool")
	@Scheduled(cron = "0 0 23 * * ?")
	public void deviceDeadlineCheck() throws ParseException {
		log.info("=============设备检查是否超时任务开始处理=============");
		List<DeviceInspection> deadlineCheckList = deviceInspectionService.getDeadlineCheckList();
		if (deadlineCheckList.isEmpty()) {
			log.info("=============没有设备正在检查=============");
			return;
		}
		Date today = DataFormatUtil.getLocalDate();
		if (Func.isNotEmpty(deadlineCheckList)) {
			ArrayList<DeviceInspection> list = new ArrayList<>();
			deadlineCheckList.forEach(deviceInspection -> {
				Date deadline = deviceInspection.getCheckDeadline();
				if (Func.isNotEmpty(deadline)) {
					if (today.after(deadline)) {
						deviceInspection.setStatus(Constant.DEVICE_STATE_OVERTIME_INSPECTION);
						list.add(deviceInspection);
					}
				}
			});
			deviceInspectionService.updateBatchById(list);
		}
		log.info("=============设备检查是否超时任务处理结束=============");
	}

	/**
	 *检查设备是否超过维保期限使用中
	 */
	@Async("securityThreadPool")
	@Scheduled(cron = "0 0 1 * * ?")
	public void deviceUsageStateCheck()  throws ParseException{
		log.info("=============检查设备是否超维保期限使用 开始处理=============");
		List<Device> deviceList = deviceService.getUsingList();
		ArrayList<Device> DeviceChecks = new ArrayList<>();
		Date today = DataFormatUtil.getLocalDate();
		if (Func.isNotEmpty(deviceList)){
			deviceList.forEach(item ->{
				if (Func.isNotEmpty(item.getMaintenanceDate()) && today.after(item.getMaintenanceDate())){
					item.setUsageState(Constant.DEVICE_STATE_OVERTIME_USE);
					DeviceChecks.add(item);
				}
			});
			deviceService.updateBatchById(DeviceChecks);
		}
		log.info("=============检查设备是否超维保期限使用 处理结束=============");
	}
}
